在列表中转换int,long,boolean,String,double(两个变体),Set(两个变体),Queue,Deque

时间:2015-08-30 18:07:45

标签: java arrays generics collections

我有一个方法将数组转换为ArrayList,如下所示:

public class Main {

    //https://docs.oracle.com/javase/tutorial/extra/generics/methods.html
    public static <T> void fromArrayToCollection(T[] a, Collection<T> c) {
        for (T o : a) {
            c.add(o);
        }
    }

    public static void main(String[] args) {
        Car [] cars = new Car[2];
        cars[0] = new Car(1, "Volvo", "2612AXA");
        cars[1] = new Car(2, "Toyota", "1861AXA");

        int [] i = new int[2];
        i[0] = 1;
        i[1] = 1;

        long [] l = new long[2];
        l[0] = 122342141;
        l[1] = 214214211;

        double [] d = new double[2];
        d[0] = 1.0;
        d[1] = 2.0;

        boolean [] b = new boolean[2];
        b[0] = true;
        b[1] = false;

        String [] s = new String[2];
        s[0] = "One";
        s[1] = "Two";

        Collection<String> sc = new ArrayList<String>();
        fromArrayToCollection(s, sc);
        System.out.println(sc);

    }
}

转换其他类型的数组很容易。但我有一些有三个领域的课。

public class Car {
    int id;
    String car_name;
    String number;

    public Car(int id, String car_name, String number) {
        this.id = id;
        this.car_name = car_name;
        this.number = number;
    }

    @Override
    public String toString() {
        return "Car{" +
                "id=" + id +
                ", car_name='" + car_name + '\'' +
                ", number='" + number + '\'' +
                '}';
    }
}

如何将阵列车转换为集合?如何使用迭代器将所有数组转换为集合?感谢。

1 个答案:

答案 0 :(得分:0)

Car[] carsArray = new Car[2];

... 

List<Car> listOfCars = Arrays.asList(carsArray);