Creating and populating an array in the easiest way

I am developing an application.

    class Wheel {
    private int size;

    Wheel(int s) {
        size = s;
    }

    void spin() {
        System.out.print(size + " inch wheel spinning, ");
    }

}

public class Bicycle {
    public static void main(String[] args) {
        Wheel[] wa = { new Wheel(15), new Wheel(17) };
        for (Wheel w : wa)
            w.spin();
    }
}

But please advise how we can express in Wheel[] wa = { new Wheel(15), new Wheel(17) };more simplified terms.

+3
source share
3 answers

If you want a shorter expression for creating an array of wheels, then you have a simple one, since it can be obtained without additional methods.

You can create a factory method, for example:

class Wheel {

    public static Wheel[] newWheels( int[] sizes ){
        Wheel[] result = new Wheel[sizes.length];
        for( int i=0; i < sizes.length; i++ )
           result[i] = new Wheel( sizes[i] );
        return result;
    }

    // ... other stuff ...
}

What would your expression about making a wheel do:

Wheel[] wa = Wheel.newWheels( new int[]{ 15, 17 } );

It is not much simpler if you have only two wheels of a given size, but if you have more of them or if you have not set sizes, it can be more readable.

0
source

Wheel[] wa = { new Wheel(15), new Wheel(17) }; , . - , , ?

, -, Wheel s, , ...

Wheel[] wa = new Wheel[2];
wa[0] = new Wheel(15);
wa[1] = new Wheel(17);

, ,...

int[] sizes = {15,17};
Wheel[] wa = new Wheel[sizes.length];
for (int i=0;i<sizes.length;i++){
    wa[i] = new Wheel(sizes[i]);
}

, , Wheel .

2 Wheel, !

+6
Wheel[] wa = { new Wheel(15), new Wheel(17) };

, .

java.util.Set<E> ( ) java.util.List<E> ( )

array (java.util.Map<K,V>). , Set or List.

    List<Wheel> wh1=new ArrayList<Wheel>(15);
    List<Wheel> wh2=new ArrayList<Wheel>(17);
    Map<String,List<Wheel>> wa=new HashMap<String,List<Wheel>>();
    wa.put("1stList", wh1);
    wa.put("2ndList", wh2);
0

All Articles