简体   繁体   中英

What is the best way to convert a raw vector to type safe list(Arraylist)

I have a function that return a raw vector. I know that all the elements in the vector are string but the code stays for leagacy reasons. I want to get a arraylist from this data.

One naive way is to iterate the vector and add elements to the list. Is there any short way of doing it which can prevent looping. Or may be a direct function which enables this.

Edit:

Example:

Vector f1() {}  //f1 returns raw vector

I want to achieve the following:

List<String> l = new ArrayList<String>();
Vector vec = f1();
for(Object obj: vec) {
    l.add((String) obj);
}

Note: I have not checked if the above code compiles. Please treat it as a pseudo code

If you are 100% sure the Vector only contains Strings, the simplest way is:

List<String> list = new ArrayList<>(vector);

Note that this will compile and run fine, even if you Vector contains other types of objects. However this:

list.get(i);

will throw a ClassCastException if the i-th element was not a String.

Since you have a raw Vector you will get warnings. If you want to get rid of them you can use:

@SuppressWarnings(value = {"unchecked", "rawtypes"})
public static List<String> rawVectorToList(Vector v) {
    return new ArrayList<>(v);
}

An alternative to detect casting issues fast is to copy the array manually (what the copy constructor does under the hood):

Vector v = ...;
String[] elements = Arrays.copyOf(v.toArray(), v.size(), String[].class);
List<String> list = Arrays.asList(elements);

or if you need the list to be mutable:

List<String> list = new ArrayList<> (Arrays.asList(elements));

This has the benefit of checking the type at copy time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM