Reputation: 21
I would like to call the first element of my Set 'set'. At this moment the content is set=["1", "2"]...When I run the following code, it return "2" in the iter.next(), is there a possibility that he returns first "1" and in the next loop "2"?
//Remove duplicates from array
Set set= new HashSet(Arrays.asList(leveranciers));
Iterator iter = set.iterator();
while (iter.hasNext()) {
//for (Iterator it = set.iterator();it.hasNext();){
PdfPTable table = GetTable(""+ iter.next());
byte[] pdf = wdThis.wdGetAchatsIndirectController().GetPDFFromFolder("/intranetdocuments/docs/AchatsIndirect", table);
wdThis.wdGetAchatsIndirectController().PrintPDF(pdf);
}
Upvotes: 0
Views: 1032
Reputation: 3058
In general, there is no 'first element' in a Set
. set.iterator().next()
will give you an arbitrary element (or null
if the set is empty). LinkedHashSet
will however let you iterate the elements in the order they were added to the set. TreeSet
will let you iterate the elements in their natural order (if they are Comparable
). Or perhaps you really want a List
?
However, would this not do what you want?
// Assuming it is strings in 'leveranciers' (as implied by set=["1", "2"])
for(String s : Arrays.asList(leveranciers)) {
PdfPTable table = GetTable("" + s);
byte[] pdf = wdThis.wdGetAchatsIndirectController().GetPDFFromFolder("/intranetdocuments/docs/AchatsIndirect", table);
wdThis.wdGetAchatsIndirectController().PrintPDF(pdf);
}
Also, as noted by Joffrey, please add in the generic types of your collections, as in Foo
, Bar
(whatever they might be) here:
Set<Foo> set = ...
Iterator<Bar> iter = ...
Upvotes: 0
Reputation: 213223
Well, a HashSet
doesn't retain the insertion order. If you want that, use LinkedHashSet
. And please use a parameterized version.
Upvotes: 3