简体   繁体   中英

How do I print out an ArrayList<Integer> from a HashSet<ArrayList<Integer>>?

I have a HashSet<ArrayList<Integer>> . Its printed format is:

[ [1, 2], [11, 22], [111, 222] ]

Now, if I just want to print out the last Array<Integer> which is [111, 222] , how do I do that? Is there any similar method to indexOf() for a HashSet ?

You can't as there is no order inside a Set, and therefore no index. So your "last" element is not always the same. If you need them to be in order you could use a LinkedHashSet .

Or you iterate over all elements of the Set and find the one you want to print like that.

Elements in a HashSet aren't stored in any defined order. So asking fo the "last" element of a HashSet doesn't make sense.

If you need an ordered set, then use a LinkedHashSet.

If you need a sorted set, then use a TreeSet.

HashSet does not maintain order, so you will not be able to use API such as indexOf() with HashSet . You need to use List in place of Set to get the indexOf() last element.

    List<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
    // Add elements in the list

    list .indexOf(list.size()-1); // This will fetch you the last element

No, but you can iterate to the last element and print it:

Iterator i = set.iterator();
List last = null;
while(i.hasNext()) 
   last = i.next();
...

Or you can transform the set into a list and get the last element:

List list = new ArrayList(set);
List last = list.get(list.size() - 1);
...

You can iterate till the last element and print only the last one.

Best way would be if you use TreeSet instead of HashSet.

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