简体   繁体   中英

How to remove the first element and make the second one be the first element immediately in java.util.NavigableSet?

I have a set of an object:

 NavigableSet<JobWithDepartTime> set = new TreeSet();

And then when I do this in the other class:

GroupMesin.JobWithDepartTime a = groupMesin[i].set.pollFirst();
groupMesin[i].set.first().getJob().printData();

it says it has an Exception (on that second line) :

Exception in thread "main" java.util.NoSuchElementException

All I want to do is take out the first element in this set, make the second element to be the first, the third to the second, and so on. How do I do that?

Any response will be apreciated.

pollFirst() actually removes the element, so what you'd want to do is this:

GroupMesin.JobWithDepartTime a = groupMesin[i].set.pollFirst();
if (a != null) //if the set is empty, pollFirst() returns null
  a.getJob().printData();

What your code was doing is remove the first element and then try to access the new first element (without removing it). When your set only had one element to begin with, this will result in a NoSuchElementException , as after removing the first element, your set will be empty.

The naming of these methods is somewhat confusing, it's first() that does what you traditionally might call peeking or polling, and pollFirst() is the method that modifies the set as well.

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