I was trying to code a simple problem which goes as follows:
This week there will be an important meeting of your entire department. You clearly remember your boss telling you about it. The only thing you forgot is the day of the week when the meeting will take place.
You asked six of your colleagues about the meeting. None of them knew the day when it will take place, but each of them remembered one day when it will not take place. The days they remembered were distinct. For a clever programmer like you, this was enough to determine the day of the meeting.
Now I have created two arrays for it, one containig all the weekdays and one containing all the days where the meeting would not take place and then created two lists from them.
public static void main(String[] args) {
String[] notOnThisDay={"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
String[] weekdays={"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
List<String> list1=Arrays.asList(weekdays);
List<String> list2=Arrays.asList(notOnThisDay);
Iterator<String> iter=list1.iterator();
while(iter.hasNext()) {
if(list2.contains(iter.next())) {
iter.remove();
}
}
for(String x:list1) {
System.out.println(x);
}
}
My strategy was to traverse through the weekdays list and if I find any day which is also present in the notonThisDay list, then I remove it. As such I am left with the day on which the meeting is to take place, but there seems to be something wrong with the iter.remove() method.
Please point out the error. And give me advice if my algorithm is good. I accept suggestions for a better algorithm if any.
Your problem is that
Arrays.asList()returns a list of fixed size. You’re better to use one of the constructors of a known type of list, such asnew ArrayList( ... )ornew LinkedList( ... ).