简体   繁体   中英

Add a new line at the end of collection

I would like to use unsorted generic collection to store values.

Set<Integer> map = new HashSet<Integer>();
map.Add( new Integer( 3 ) );
map.Add( new Integer( 2 ) );
map.Add( new Integer( 4 ) );
map.Add( new Integer( 1 ) );

I suppose the elements would be 3,2,4,1. Then I would like to create an array from this set:

Integer[] arr = ( Integer[] )map.toArray( new Integer[map.size()] );

And I'm surprised because the elements in arr are in different order than I put into map. The deal is to get an array like this:

arr[0] = 3;
arr[1] = 2;
arr[2] = 4;
arr[3] = 1;

What should I do for this?

HashSet does not guarantee that the order will remain same. If you want to maintain order then use ArrayList .

Sets are unordered. It is not guaranteed to maintain the order of the elements. You need to use a list if the order you added the elements should remain the same.

List<Integer> map = new ArrayList<Integer>();
map.add( new Integer( 3 ) );
map.add( new Integer( 2 ) );
map.add( new Integer( 4 ) );
map.add( new Integer( 1 ) );

use LinkedHashSet instead of HashSet

    Set<Integer> map = new LinkedHashSet<Integer>();
    map.add( new Integer( 3 ) );
    map.add( new Integer( 2 ) );
    map.add( new Integer( 4 ) );
    map.add( new Integer( 1 ) );

    Integer[] arr = ( Integer[] )map.toArray( new Integer[map.size()] );

    System.out.println(Arrays.toString(arr));

您可以使用LinkedHashSet保留输入顺序:

Set<Integer> map = new LinkedHashSet<Integer>();

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