Why am I entering a loop? - java

It works fine and gives me the correct output until it enters the last object to add to nonEmptyList in the sample() method. I have managed to find out where it is looping, which is in the while loop in the add(item) method. I can't change the methods or returns, so if anyone could suggest a way I could prevent this infinite loop, that would be appreciated.
public class SampleableListImpl implements SampleableList {
public int size;
public Object firstLink = null; //Made a link class to manage each object, this class is the linkedlist (manager) of the object private
public ReturnObjectImpl ro;
int count;
SampleableListImpl emptyList;
SampleableListImpl nonEmptyList;
public ReturnObject add(Object item) {
if (firstLink == null){
firstLink = item;
size++;
firstLink.setIndex(0);
System.out.println("Added linkedlink at 0");
} else if (firstLink != null){
Object current = firstLink;
while (current.getNextNode() != null){ //LOOPS HERE AFTER sample() sends the last object to be added to nonEmptyList
current = current.getNextNode();
}
current.setNextNode(item);
size++;
current.getNextNode().setIndex(size - 1);
System.out.println("Added a new link to the existing linkedlist at " + current.getNextNode().getIndex());
}
return null;
}
public SampleableList sample() {
if (firstLink == null){
System.out.println("List is empty, so returning an empty sampableList");
return emptyList = new SampleableListImpl();
}
Object current = firstLink;
if (firstLink.getNextNode().getNextNode() != null){
nonEmptyList = new SampleableListImpl();
System.out.println("Adding to firstNode in nonEmptyList");
nonEmptyList.add(firstLink);
while (current.getNextNode().getNextNode() != null){
current = current.getNextNode().getNextNode();
System.out.println("Adding " + current.getIndex() + " to nonEmptyList");
nonEmptyList.add(current);
}
} else {
nonEmptyList.firstLink = current;
System.out.println("There is only a head - no other objects to sample");
}
System.out.println("returning nonEmptyList");
return nonEmptyList;
}
}
And I am running this
SampleableListImpl sampList = new SampleableListImpl();
Object ob = new Object();
Object ob1 = new Object();
Object ob2 = new Object();
Object ob3 = new Object();
Object ob4 = new Object();
sampList.add(ob);
sampList.add(ob1);
sampList.add(ob2);
sampList.add(ob3);
sampList.add(ob4);
sampList.sample();

When all 5 objects are added just before call sample():
ob.getNextNode() will return ob1.
ob1.getNextNode() will return ob2.
ob2.getNextNode() will return ob3.
ob3.getNextNode() will return ob4.
ob4.getNextNode() will return null.
sample() will in the first loop add ob again:
ob.getNextNode() will return ob1.
ob1.getNextNode() will return ob2.
ob2.getNextNode() will return ob3.
ob3.getNextNode() will return ob4.
ob4.getNextNode() will return ob.
In the second loop within sample() it will try to add ob2, but it can no longer reach the end of your list.
What you could do to get around this, is create a copy of each object you want to add from sample() (and set their next node to null before adding).

Related

How do I write an addElement method to a sorted LinkedList?

I have an assignment that goes:
implement a linked list of String objects by use of the class Node (see Big >Java Early Objects 16.1.1). Write methods, that make it possible to insert >and delete objects, as well as print all objects in the list. It is a >requirement that all elements in the list are sorted, at all times, according >to the natural ordering of Strings(Comparable).
The method that I can't seem to get right, is the addElement method
The entire class is here: https://pastebin.com/Swwn8ykZ
And the mainApp: https://pastebin.com/A22MFDQk
I've looked through the book (Big Java Early Objects), as well as looked on geeksforgeeks
public void addElement(String e) {
Node newNode = new Node();
if (first.data == null) {
first.data = e;
System.out.println("Success! " + e + " has been
added!");
} else if (first.data.compareTo(e) == 0) {
System.out.println("The element already exists in the
list");
} else {
while (first.next != null) {
if (first.next.data.compareTo(e) != 0) {
first.next.data = e;
} else {
first.next = first.next.next;
}
}
}
}
public static void main(String[] args) {
SortedLinkedList list = new SortedLinkedList();
String e1 = new String("albert");
String e2 = new String("david");
String e3 = new String("george");
String e4 = new String("jannick");
String e5 = new String("michael");
// ----------------SINGLE LIST--------------------------
list.addElement(e1);
list.addElement(e2);
list.addElement(e3);
list.addElement(e4);
list.addElement(e5);
System.out.println("Should print elements after this:");
list.udskrivElements();
}
}
Expected result: The five names printed in a list
Actual result: The first name printed
Given this Node class:
private class Node {
public String data;
public Node next;
}
and a class-level field of private Node first; that is initially null to signal an empty list,
the addElement could be like this:
public void addElement(String text) {
if (text == null) return; // don't store null values
Node extra = new Node();
extra.data = text;
if (first == null) {
// no list yet, so create first element
first = extra;
} else {
Node prev = null; // the "previous" node
Node curr = first; // the "current" node
while (curr != null && curr.data.compareTo(text) < 0) {
prev = curr;
curr = curr.next;
}
if (curr == null) {
// went past end of list, so append
prev.next = extra;
} else if (curr.data.compareTo(text) == 0) {
System.out.println("Already have a " + text);
} else {
// between prev and curr, or before the start
extra.next = curr;
if (prev != null) {
prev.next = extra;
} else {
// append before start, so 'first' changes
first = extra;
}
}
}
}
By the way, also try and add the names in an unsorted order to check that the list sorts them (I found a bug in my code when I tried that).

Doubly Linked Lisl keeps getting null pointer error

I looked at all of the previous examples and cant see anything that I am doing wrong. I really struggle with null pointer exceptions for some reason and I just cant wrap my head around them.
public class DLBDictionary implements DictionaryInterface {
//Store Strings in an Node
public DLBNode firstNode;
public class DLBNode
{
public char value;
public DLBNode nextValue;
public DLBNode nextLetter;
public DLBNode(){
this.value = '/';
this.nextValue = null;
this.nextLetter = null;
}
public DLBNode(char value){
this.value = value;
this.nextValue = null;
this.nextLetter = null;
}
}
public DLBDictionary() {
DLBNode firstNode = new DLBNode('/');
}
// Add new String to end of list. If String should come before
// previous last string (i.e. it is out of order) sort the list.
// We are keeping the data sorted in this implementation of
// DictionaryInterface to make searches a bit faster.
public boolean add(String s) {
int charIndex = 0;
while(charIndex<=s.length())
{
char currentChar = s.charAt(charIndex);
boolean added = false;
while(!added)
{
if(firstNode.value == '/')
{
firstNode.value = currentChar;
added = true;
}
else if(firstNode.value == currentChar)
{
if(firstNode.nextLetter == null)
{
DLBNode newNode = new DLBNode();
firstNode.nextLetter = newNode;
firstNode = firstNode.nextLetter;
}
else
{
firstNode = firstNode.nextLetter;
}
added = true;
}
else
{
firstNode = firstNode.nextValue;
}
}
charIndex++;
}
DLBNode tempNode = new DLBNode('^');
firstNode.nextLetter = tempNode;
return true;
}
I left off the rest of my code but that last if statement is where I get the exception. It makes no sense to me! Didn't I initialize firstNode's value to '/' in the constructor? So firstNode.getValue should return '/' not a null pointer exception.
You should do
this.firstNode = new DLBNode();
in the constructor of DLBDictionary. You are actually creating a new object rather initializing your firstNode. Hope it helps.
You reset firstNode with several statements in the loop:
firstNode = firstNode.nextValue;
So it will happen that firstNode == null and this causes the NPE. The char value has nothing to do with it, it will be initialised to a character with value 0x00 anyway.

How do I add objects into a linked list?

I have been working on a project where I must implement a java class that implements the use of doubly linked lists. I have the LinkedList class finished with all my methods. I'm just unsure how to actually add node objects into the list. Here is my code so far with test at the bottom. Any help would be appreciated. Thanks
public class LinkedList {
private Node first;
private Node current;
private Node last;
private int currentIndex;
private int numElements;
public LinkedList() {
this.first = null;
this.last = null;
this.numElements = 0;
this.current = null;
this.currentIndex = -1;
}
private class Node {
Node next;
Node previous;
Object data;
}
public boolean hasNext() {
return (current != null && current.next != null);
}
public Object next() {
if (!this.hasNext()) {
throw new IllegalStateException("No next");
}
current = current.next;
return current.data;
}
public boolean hasPrevious() {
return (current != null && current.previous != null);
}
public Object previous() {
if (!this.hasPrevious()) {
throw new IllegalStateException("No previous");
}
current = current.previous;
return current.data;
}
int nextIndex() {
int index = numElements;
if (hasNext()) {
index = this.currentIndex + 1;
}
System.out.println(index + "The current index is " + current);
return index;
}
int previousIndex() {
int index = -1;
if (hasPrevious()) {
index = this.currentIndex - 1;
}
System.out.println(index + "The current index is " + current);
return index;
}
public void set(Object o) {
if (this.current == null) {
throw new IllegalStateException("No node found, cannot set.");
}
current.data = o;
}
public int size() {
return numElements;
}
public void add(Object o) {
Node newNode = new Node();
newNode.data = o;
if (first == null) {
first = newNode;
last = newNode;
newNode.next = null;
} else if (first != null) {
if (current == null) {
newNode.previous = null;
newNode.next = first;
first.previous = newNode;
first = newNode;
} else if (current == last) {
newNode.previous = current;
newNode.next = null;
current.next = newNode;
last = newNode;
} else {
newNode.previous = current;
newNode.next = current.next;
current.next.previous = newNode;
current.next = newNode;
}
}
current = newNode;
numElements++;
currentIndex++;
}
public void remove() {
if (current != null) {
if (current == first && current == last) {
first = null;
last = null;
} else if (current == last) {
current.previous = null;
last = current.previous;
} else if (current == last) {
current.previous.next = null;
last = current.previous;
} else {
current.previous.next = current.next;
current.next.previous = current.previous;
}
current = current.next;
numElements--;
}
}
}
import java.util.Scanner;
public class LinkedListTest {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String name;
int index;
LinkedList<Object> listOne = new LinkedList<Object>();
listOne.add(object o);
}
}
The posted class LinkedList looks functional to me.
Make sure that your test code does not confuse this class and java.util.LinkedList, which Java provides for you (It's a part of the existing Collections framework).
For clarity, I would recommend renaming your class to something like MyLinkedList
The following code works and the output is "0","2":
public class MyLinkedListTest {
public static final void main(String[] args) {
MyLinkedList list = new MyLinkedList();
System.out.println("Number of items in the list: " + list.size());
String item1 = "foo";
String item2 = "bar";
list.add(item1);
list.add(item2);
System.out.println("Number of items in the list: " + list.size());
// and so on...
}
}
I'd be surprised if your code compiled, since your class isn't actually generic. Just initialize it as LinkedList listOne = new LinkedList(); (no angle brackets).
As to actually adding elements, you just need an instance of some Object to add; anything will do (assuming your internal code works properly). Try this down at the end there:
Object objectToAdd = "Strings are Objects";
listOne.add(objectToAdd);
objectToAdd = new File("C:\\foo.bar"); // Or use any other Objects!
listOne.add(objectToAdd);
Think of numbered list and look at the relations between the elements
Say I have the list:
A
B
C
What do I have to do to the relations get the list:
A
B
NewNode
C
The new next node of B is NewNode
The new previous node of C is NewNode. So an insert function would want to know the immediate previous node or the immediate next node and then adjust the relationships.
Your LinkedList doesn't have generic types so you can't declare it as
LinkedList<Object> listOne = new LinkedList<Object>();
but rather as
LinkedList listOne = new LinkedList();
And now to add elements just use your add method
listOne.add("something");
listOne.add(1);//int will be autoboxed to Integer objects
Also if you want to add data from keyboard you can use something like
String line="";
do{
System.out.println("type what you want to add to list:");
line = keyboard.nextLine();
listOne.add(line);
}while(!line.equals("exit"));
The line
LinkedList<Object> listOne = new LinkedList<Object>();
won't compile unless you change your class declaration to
class LinkedList<T>
or alternately you can just write
LinkedList listOne = new LinkedLis();
After that you should be able to add objects to your list. However, you'll need to create an Object to add to it, listOne.add(object o); won't do--at the very least you'll have to write listOne.add(new Object()). (Your code does not instantiate an Object, there is no Object that you already have called o, and besides, object o does not mean anything in Java and would not compile.
As people have mentioned your list is not generic. However as they advise you to get rid of the parameter, you can also just add <Object> or <E> to your linked list implementation and leave your initialization of the list as it is.
So in your linked list class you should do something like:
public class LinkedList<E>
This will make sure when you're using LinkedList<Object> listOne = new LinkedList<Object>();, E will be covnerted to Object
Let's improve your test a little bit so that it becomes apparent where your problems are (if any) I commented out the call to the current() method since you have not included one. (I would leave this alone as it may confuse you.) The general idea would be to add items to the linked list and walk forward and backward through it checking the items with each step.
public class LinkedListTest {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String name;
int index;
LinkedList listOne = new LinkedList();
//Initially we should be empty so we are positioned
// at both the beginning and end of the list
assert listOne.size() == 0 :"List should be empty";
assert listOne.hasPrevious()==false: "Should be at the beginning of the list";
assert listOne.hasNext()==false : "Should be at the end of the list";
Object firstNode = "I am the first node";
listOne.add(firstNode); //we've added something
//I left this commented out since you don't have a current() method.
// assert firstNode == listOne.current() : "Our current item should be what we just added";
assert listOne.hasPrevious()==false : "Should not have moved forward in our list yet";
assert listOne.hasNext()==true : "should have an item after our current";
assert listOne.size() == 1 : "Should only have one item in the list";
Object secondNode = "I am the second node";
listOne.add(secondNode);
assert listOne.size() == 2 : "Should only have two items in the list";
assert firstNode == listOne.next() : "1st call to next should return the 1st node";
assert listOne.hasPrevious()==true : "We should be positioned after the 1st node";
assert listOne.hasNext()==true : "We should be positioned before the 2nd node";
}
}

Null pointer exception in iterating and unable to search a node. The delete and replace methods are the ones that have problems

import javax.swing.*;
import java.io.*;
class MyDatabase implements Database {
Node head = null, tail = null, rover = null;
String ako;
File myFile = new File("sample.dat");
Node n = new Node();
Node current; Node p;
Node x = new Node();
public void insert(Node myNewNode) {
if (head == null){
head = myNewNode;
head.next = null;
}
else {
tail = head;
while(tail.next != null)
tail = tail.next;
tail.next = myNewNode;
myNewNode.next = null;
}
current = head;
}
public boolean delete(Node nodeToDelete) {
//the delete and replace methods are the ones that have problems
current = head;
p = head;
head = null;
//here, no matter what you enter, this if statement is never executed. Yes, never. even if they are equal.
if(nodeToDelete.title == head.title) {
head = head.next;
return true;
}
else{
while(current != nodeToDelete)
current = current.next;//Null Pointer exception here
while(p.next != nodeToDelete)
p = p.next;//Null Pointer exception here
current = current.next;
p = current;
}
current = head;//this is for listIterator purposes.
return true;
}
public boolean replace(Node nodeToReplace, Node myNewNode) {
//the delete and replace methods are the ones that have problems
//here i tested if the head.title and nodeToReplace.title have values
//the println correctly prints the value that I input
current = head;
String s = head.title;// for example i entered "max"
String s1 = nodeToReplace.title;// i also entered "max"
System.out.println(s);//prints out "max"
System.out.println(s1);// prints out "max"
if(s == s1) { // if statement is not executed. Note: i entered the same string.
myNewNode.next = head.next;
head = myNewNode;
}
else {
while(current != null) {
String s2 = current.title;
if(s2 == s1) {
current = new Node(myNewNode);
}
}
}
current = head;
return true;
}
public Node search(Node nodeToSearch) {
current = head;
while(current != null) {
if(current == nodeToSearch) {
Node p = new Node(current);
current = head;
return p;
}
}
return null;
}
public boolean saveToFile(String filename) throws Exception {
Node p = new Node();
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(myFile));
out.writeObject(p);
out.close();
return true;
}
public boolean loadFromFile(String filename) throws Exception {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(myFile));
head = (Node) in.readObject();
return true;
}
public Node listIterator() {
try{
if(current == head) {
rover = current;
current = current.next;
return rover;
}
else {
rover = current;
current = current.next;
Node p = new Node(rover);
return p;
}
}
catch(NullPointerException e) {
current = head;
return null;
}
}
public Node listIterator2() {
try{
if(current == head) {
rover = current;
current = current.next;
return rover;
}
else {
rover = current;
current = current.next;
return rover;
}
}
catch(NullPointerException e) {
current = head;
return null;
}
}
public boolean equals(Database db) {
Node p;
while(rover != null) {
p = head;
while(p != null) {
if(rover != p)
return false;
p = p.next;
}
rover = rover.next;
}
return true;
}
public String whoIAm() {
ako = "Michael Glenn R. Roquim Jr. !";
return ako;
}
}
You trigger your own NPE:
// vv-- here you set head to null, just before you dereference it to access .title
head = null;
//here, no matter what you enter, this if statement is never executed. Yes, never. even if they are equal.
if(nodeToDelete.title == head.title) {
head = null;
//here, no matter what you enter, this if statement is never executed. Yes, never. even if they are equal.
if(nodeToDelete.title == head.title) {
you set head to null and immidiately after it you try to access it... (head is always null, so head.title will throw NPE)
also:
if(s == s1) { // if statement is not executed. Note: i entered the same string.
use equals() while comparing string, and not == (because otherwise you are looking for a same exact reference and not the same "string").
one more thing: it seems you will always throw NPE (when deleting) if your element is not in the list (you will not find the element, reach the end of the list which is null, and then try to address an instance variable in it).
I like cutting down code to the essentials so here is a working version which just does what the methods suggest.
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
class MyDatabase {
private final List<Book> titles = new ArrayList<Book>();
public void insert(Book title) {
titles.add(title);
}
public boolean delete(Book title) {
return titles.remove(title);
}
public boolean replace(Book title1, Book title2) {
int pos = titles.indexOf(title1);
if (pos >= 0) {
titles.set(pos, title2);
return true;
}
return false;
}
public Book search(String title) {
for (Book book : titles) {
if (book.title.equals(title))
return book;
}
return null;
}
public void saveToFile(String filename) throws IOException {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename));
out.writeObject(titles);
out.close();
}
public void loadFromFile(String filename) throws IOException, ClassNotFoundException {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename));
titles.clear();
titles.addAll((List) in.readObject());
in.close();
}
public ListIterator<Book> listIterator() {
return titles.listIterator();
}
public boolean equals(Object o) {
return o instanceof MyDatabase && ((MyDatabase) o).titles.equals(titles);
}
public String whoIAm() {
return "Michael Glenn R. Roquim Jr. !";
}
}
class Book {
final String title;
final int year;
Book(String title, int year) {
this.title = title;
this.year = year;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Book book = (Book) o;
if (year != book.year) return false;
if (!title.equals(book.title)) return false;
return true;
}
}
Hmm, several problems here.
You set head to null, then promptly reference head.title. This will always throw a null pointer exception. I see someone else pointed that out.
You attemt to compare strings with ==. This won't work, it compares the address of the string, not the contents. Use equals.
When you check if the node matches the head node, you compare the titles. But when you compare to any other node, you do == on the node itself. You shouldn't have two different methods to compare nodes. As noted above, the title==title won't work. node==node might or might not work. How do you get a node to delete? If it is really the same node, i.e. the same object, as the node in the list that you are trying to delete, that's fine. But if it is a node constructed from, say, a user input, and so it will have maybe the same title as a node in the list, but not actually be the same object, this won't work. You probably want to say node.equals(node) and define an equals() function on node.
You set current to head and p to head, then you search starting from current, then you search starting from p. These should give identical results. Why do it twice?
If you don't find the node, you eventually hit a next value equal to null, but you just keep looking, thus generating a null-pointer exception.
As a point of style, it is better to define a variable within a function rather than as a member variable whenever possible.
Finally, may I suggest a little trick: Instead of having special handling for head all over the place, create a "sentinel", a fake node whose next pointer points to head. This really simplifies the code. For example:
class MyLinkedList
{
Node sentinel;
public MyLinkedList()
{
sentinel=new Node();
sentinel.next=null;
}
public void insert(Node myNewNode)
{
// This assumes new nodes must be added at the end. With a single-linked
// list, this requires traversing the entire list to reach the end.
Node current;
/* Note sentinel is never null, so we don't need any special handling here.
If the list is empty, sentinel.next is null, but that doesn't create
a special case.
*/
for (current=sentinel; current.next!=null; current=current.next) ;
current.next=myNewNode;
myNewNode.next=null;
}
public void insertAtStart(Node myNewNode)
{
// If we can add new nodes to the beginning, this is much faster.
myNewNode.next=sentinel.next;
sentinel.next=myNewNode;
}
public boolean delete(Node nodeToDelete)
{
Node current;
for (current=sentinel; current.next!=null; current=current.next)
{
if (current.next.equals(nodeToDelete)
{
current.next=current.next.next;
return true;
}
}
return false;
}
... etc ...

Java Queue Merge, Beginner

I'm trying to write a method that will take in two Queues (pre-sorted Linked Lists) and return the merged, in ascending order, resulting Queue object. I pasted the Queue class, the merge method starts 1/2 way down.
I'm having trouble calling merge, this is how I am trying to call it from my main method, can anyone help with this call with new1 and new2. Thanks so much Everyone!
Please let me know if anyone notices anything else out of place. Thanks!
///////////////// //Testing with a call of merge method & 2 Queues///////////////////
public class test {
public static void main (String args[]){
Queue new1 = new Queue();
new1.enqueu(1);
new1.enqueu(3);
new1.enqueu(5);
Queue new2 = new Queue();
new1.enqueu(2);
new1.enqueu(4);
new1.enqueu(6);
merge(new1, new2);
//How to call merge? Queue.merge(new1, new2)???
/////////////////Queue/Merge method below////////////////////////
public class Queue {
private Node first, last;
public Queue(){
first = null;
last = null;
}
public void enqueu(int n){
Node newNode = new Node(n);
if (first == null)
{
first = newNode;
last = newNode;
}
else
{
last.setNext(newNode);
last = newNode;
}
}
public int dequeue(){
int num = first.getNum();
first = first.getNext();
if(first == null)
last = null;
return num;
}
public Boolean isEmpty() { return first == null; }
////////////////////////Begin Queue merge/////////////////////////////////
Queue merge(Queue q1, Queue q2) {
Queue result = new Queue();
boolean q1empty = q1.isEmpty();
boolean q2empty = q2.isEmpty();
while (!(q1empty || q2empty)) {
if (q1.first.getNum() < q2.first.getNum()) {
result.enqueu(q1.dequeue());
q1empty = q1.isEmpty();
} else {
result.enqueu(q2.dequeue());
q2empty = q2.isEmpty();
}
}
if (!q1empty) {
do {
result.enqueu(q1.dequeue());
} while (!q1.isEmpty());
} else if (!q2empty) {
do {
result.enqueu(q2.dequeue());
} while (!q2.isEmpty());
}
return result;
}}
You have what appears to be a bug here:
Queue new1 = new Queue();
new1.enqueu(1);
new1.enqueu(3);
new1.enqueu(5);
Queue new2 = new Queue();
new1.enqueu(2);
new1.enqueu(4);
new1.enqueu(6);
You've added six elements to new1 and zero to new2.
Since your merge method is an instance method of the Queue class, you need to call it on an instance of Queue, such as
Queue q = new Queue();
Queue merged = q.merge(new1, new2);
However since merge appears to have no side-effects and does not alter any state of the Queue instance, you probably want to just make this method static so that it belongs to the Queue class and not an instance of Queue. For example:
static Queue merge(Queue q1, Queue q2) {
...
}
//in main()...
Queue merged = Queue.merge(new1, new2);
A simple approach to merging two sorted Iterators into another Iterator:
public static Iterator<Object> merge(final Iterator<Object> it1,
final Iterator<Object> it2, final Comparator<Object> comp) {
return new Iterator<Object>() {
private Object o1 = it1.hasNext() ? it1.next() : null, o2 = it2
.hasNext() ? it2.next() : null;
#Override
public boolean hasNext() {
return o1 != null || o2 != null;
}
#Override
public Object next() {
if (o1 == null && o2 == null)
throw new NoSuchElementException();
Object ret;
if (o1 == null) {
ret = o2;
o2 = it2.hasNext() ? it2.next() : null;
} else if (o2 == null) {
ret = o1;
o1 = it1.hasNext() ? it1.next() : null;
} else {
if (comp.compare(o1, o2) <= 0) {
ret = o1;
o1 = it1.hasNext() ? it1.next() : null;
} else {
ret = o2;
o2 = it2.hasNext() ? it2.next() : null;
}
}
return ret;
}
#Override
public void remove() {
throw new UnsupportedOperationException("Not implemented");
}
};
}

Categories