Solved

Java LinkedList

Posted on 2012-03-18
20
461 Views
Last Modified: 2012-03-25
Dear Java expert, pls help me on the below:
Now after user input, If user input the score > score on the top stack, then top stack will be deleted and insert the new score else no insert. If got new score had been insert then need to do sorting. is the below LinkedList able to do that?



import java.util.*;
import javax.swing.*;

class Link {
    public String dName; // data item
    public int dLevel, dScore, dLine;   //data item    
    public Link next; // next link in list

// -------------------------------------------------------------
public Link(String name, int level, int score, int line){ // constructor
    dName = name;
    dLevel = level;
    dScore = score;
    dLine = line;
    }


// -------------------------------------------------------------
public void displayLink(){ // display ourself
    System.out.print(" Name: " + dName);
    System.out.print(", Level: " + dLevel);
    System.out.print(", Score: " + dScore);
    System.out.print(", Line: " + dLine);
    System.out.println ();
}
} // end class Link
////////////////////////////////////////////////////////////////
class LinkList
{
private Link first; // ref to first item on list
// -------------------------------------------------------------

public LinkList() // constructor
{ first = null; } // no items on list yet
// -------------------------------------------------------------

public boolean isEmpty() // true if list is empty
{ return (first==null); }
// -------------------------------------------------------------
public void insertFirst(String name, int level, int score, int line) // insert at start of list
{ // make new link
Link newLink = new Link(name, level, score, line);
newLink.next = first; // newLink --> old first
first = newLink; // first --> newLink
}
// -------------------------------------------------------------
public Link deleteFirst() // delete first item
{ // (assumes list not empty)
Link temp = first; // save reference to link
first = first.next; // delete it: first-->old next
return temp; // return deleted link
}
// -------------------------------------------------------------
public void displayList()
{
Link current = first; // start at beginning of list
while(current != null) // until end of list,
{
current.displayLink(); // print data
current = current.next; // move to next link
}
System.out.println("");

}
// -------------------------------------------------------------
} // end class LinkList
////////////////////////////////////////////////////////////////
class LinkStack
{
private LinkList theList;
//--------------------------------------------------------------
public LinkStack() // constructor
{
theList = new LinkList();
}
//--------------------------------------------------------------
public void push(String name, int level, int score, int line) // put item on top of stack
{
theList.insertFirst(name, level, score, line);
}
//--------------------------------------------------------------
public Link pop() // take item from top of stack
{
return theList.deleteFirst();
}
//--------------------------------------------------------------
public boolean isEmpty() // true if stack is empty
{
return ( theList.isEmpty() );
}
//--------------------------------------------------------------
public void displayStack()
{
System.out.println(" Stack (top-->bottom): ");
theList.displayList();
}

class scoreInput {
    int dInput;
   
    public scoreInput(int input){
    dInput = input;
    If(dInput > score )
}
//--------------------------------------------------------------
} // end class LinkStack
////////////////////////////////////////////////////////////////
class LinkStackApp
{
public static void main(String[] args)
{
LinkStack theStack = new LinkStack(); // make stack

theStack.push("Jazzy", 8, 25081, 211); // push items
theStack.push("Peter", 7, 24099, 202);
theStack.push("Dave", 6,622188,199);
theStack.push("Cindy", 5, 20765, 178);
theStack.push("Jaskiret", 4 ,18882, 165);
theStack.push("Robbie", 4, 17399, 145);
theStack.push("Elton", 3, 14328, 134);
theStack.push("Mel", 3, 12590, 125);
theStack.push("Prince", 3, 9439, 102);
theStack.push("Aaron", 2, 5628, 88);

theStack.displayStack(); // display stack

String name = JOptionPane.showInputDialog(null,"Name :");
String level = JOptionPane.showInputDialog(null,"Level :");
int proclevel = Integer.parseInt(level);

String score = JOptionPane.showInputDialog(null,"Score :");
int procscore = Integer.parseInt(score);

String line = JOptionPane.showInputDialog(null,"Line :");
int procline = Integer.parseInt(line);


} // end main()
} // end class LinkStackApp

////////////////////////////////////////////////////////////////
0
Comment
Question by:swpui
  • 12
  • 8
20 Comments
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
I don't think you need any Stack for that - it is easy to implement with with TreeSet

see the code below:

if you add the ekeelement with score less than minimal - it will not be added
if you add the Link with the score higerh than minimu - it will be added and the one with the lowes score will be elimeinated
import java.util.*;
import javax.swing.*;

class Link {
    public String dName; // data item
    public int dLevel, dScore, dLine;   //data item     
    public Link next; // next link in list

// -------------------------------------------------------------
public Link(String name, int level, int score, int line){ // constructor
    dName = name; 
    dLevel = level;
    dScore = score;
    dLine = line;
    }


// -------------------------------------------------------------
public void displayLink(){ // display ourself
    System.out.print(" Name: " + dName);
    System.out.print(", Level: " + dLevel);
    System.out.print(", Score: " + dScore);
    System.out.print(", Line: " + dLine);
    System.out.println ();
}
public int getScore(){
    return dScore;
}


} // end class Link
////////////////////////////////////////////////////////////////
class MyLinkComparator implements Comparator<Link>{

    public int compare(Link a1, Link a2){
                  if(a2.getScore() > a1.getScore())return 1;
        else if(a2.getScore() == a1.getScore())return 0;
        else return -1;
    }


}




class LinkList
{
private Link first; // ref to first item on list
// -------------------------------------------------------------

public LinkList() // constructor
{ first = null; } // no items on list yet
// -------------------------------------------------------------

public boolean isEmpty() // true if list is empty
{ return (first==null); }
// -------------------------------------------------------------
public void insertFirst(String name, int level, int score, int line) // insert at start of list
{ // make new link
Link newLink = new Link(name, level, score, line);
newLink.next = first; // newLink --> old first
first = newLink; // first --> newLink
}
// -------------------------------------------------------------
public Link deleteFirst() // delete first item
{ // (assumes list not empty)
Link temp = first; // save reference to link
first = first.next; // delete it: first-->old next
return temp; // return deleted link
}
// -------------------------------------------------------------
public void displayList()
{
Link current = first; // start at beginning of list
while(current != null) // until end of list,
{
current.displayLink(); // print data
current = current.next; // move to next link
}
System.out.println("");

}
// -------------------------------------------------------------
} // end class LinkList
////////////////////////////////////////////////////////////////
class LinkStack
{
private TreeSet<Link> theList;
//--------------------------------------------------------------
public LinkStack(TreeSet<Link> ts) // constructor
{
theList = ts;
}
//--------------------------------------------------------------
    /*
    public void push(String name, int level, int score, int line) // put item on top of stack
{
theList.insertFirst(name, level, score, line);
}
//--------------------------------------------------------------
public Link pop() // take item from top of stack
{
return theList.deleteFirst();
}
//--------------------------------------------------------------
public boolean isEmpty() // true if stack is empty
{
return ( theList.isEmpty() );
}
*/

//--------------------------------------------------------------
public void push(Link anew){
    theList.add(anew);
   theList.remove(theList.last());
}



public void displayStack()
{
System.out.println(" Stack (top-->bottom): ");
//theList.displayList();
    for(Link a: theList){
        a.displayLink();
    }

}

class scoreInput {
    int dInput;
    
    public scoreInput(int input){
    dInput = input;
  //  If(dInput > score )
}
//--------------------------------------------------------------
} // end class LinkStack
}
////////////////////////////////////////////////////////////////
public class LinkStackApp
{
public static void main(String[] args)
{
TreeSet<Link> ts = new TreeSet<Link>(new MyLinkComparator());
    ts.add(new Link("Jazzy", 8, 25081, 211));


// make stack

 // push items
ts.add(new Link("Peter", 7, 24099, 202));
ts.add(new Link("Dave", 6,622188,199));
ts.add(new Link("Cindy", 5, 20765, 178));
ts.add(new Link("Jaskiret", 4 ,18882, 165));
ts.add(new Link("Robbie", 4, 17399, 145));
ts.add(new Link("Elton", 3, 14328, 134));
ts.add(new Link("Mel", 3, 12590, 125));
ts.add(new Link("Prince", 3, 9439, 102));
ts.add(new Link("Aaron", 2, 5628, 88));


    LinkStack theStack = new LinkStack(ts);

theStack.displayStack(); // display stack

String name = JOptionPane.showInputDialog(null,"Name :");
String level = JOptionPane.showInputDialog(null,"Level :");
int proclevel = Integer.parseInt(level);

String score = JOptionPane.showInputDialog(null,"Score :");
int procscore = Integer.parseInt(score);

String line = JOptionPane.showInputDialog(null,"Line :");
int procline = Integer.parseInt(line);

    Link anew = new Link(name, proclevel, procscore, procline);

    theStack.push(anew);

    theStack.displayStack();


} // end main()
} // end class LinkStackApp

Open in new window

0
 

Author Comment

by:swpui
Comment Utility
appreciate your suggestion, I need to try linked list but not treeset.......I want to know the difference when I do in linked list and array, below are my incomplete array to show you:

import java.util.*;
import javax.swing.*;


class Person

{
private String tName;
private int tLevel, tScore, tLine;

//-----------------------------------------------------------
public Person(String name, int level, int score, int line){
tName = name;
tLevel = level;
tScore = score;
tLine = line;
}
//-----------------------------------------------------------
public void displayPerson()
{
System.out.print(" Name: " + tName);
System.out.print(", Level: " + tLevel);
System.out.print(", Score: " + tScore);
System.out.print(", Line: " + tLine);
System.out.println ();
}
//-----------------------------------------------------------
public String getLast() // get last name
{ return tName; }
} // end class Person


class ArrayInOb
{
private Person[] a; // ref to array a
private int nElems; // number of data items
//--------------------------------------------------------------
public ArrayInOb(int max) {
a = new Person[max]; // create the array
nElems = 0; // no items yet
}
//--------------------------------------------------------------
// put person into array
public void insert(String name, int level, int score, int line){
a[nElems] = new Person(name, level, score, line);
nElems++; // increment size
}
//--------------------------------------------------------------
public void display() // displays array contents
{
for(int j=0; j<nElems; j++) // for each element,
a[j].displayPerson(); // display it
System.out.println("");
}
//--------------------------------------------------------------
public void insertionSort()
{
int in, out;
for(out=1; out<nElems; out++) // out is dividing line
{
Person temp = a[out]; // remove marked person
in = out; // start shifting at out
while(in>0 && // until smaller one found,
a[in-1].getLast().compareTo(temp.getLast())>0)
{
a[in] = a[in-1]; // shift item to the right
--in; // go left one position
}
a[in] = temp; // insert marked item
} // end for
} // end insertionSort()
//--------------------------------------------------------------
} // end class ArrayInOb
////////////////////////////////////////////////////////////////
class ScoreApp
{

public static void main(String[] args){
//    Scanner console = new Scanner(System.in);
//            System.out.print("Name: ");
//            String tName = console.next();
            //Person person1 = new Person(tName);
   
int maxSize = 10; // array size
ArrayInOb arr; // reference to array
arr = new ArrayInOb(maxSize); // create the array
arr.insert("Jazzy", 8, 25081, 211);
arr.insert("Peter", 7, 24099, 202);
arr.insert("Dave", 6,622188,199);
arr.insert("Cindy", 5, 20765, 178);
arr.insert("Jaskiret", 4 ,18882, 165);
arr.insert("Robbie", 4, 17399, 145);
arr.insert("Elton", 3, 14328, 134);
arr.insert("Mel", 3, 12590, 125);
arr.insert("Prince", 3, 9439, 102);
arr.insert("Aaron", 2, 5628, 88);
arr.display();


String name = JOptionPane.showInputDialog(null,"Name :");
String level = JOptionPane.showInputDialog(null,"Level :");
int proclevel = Integer.parseInt(level);

String score = JOptionPane.showInputDialog(null,"Score :");
int procscore = Integer.parseInt(score);

String line = JOptionPane.showInputDialog(null,"Line :");
int procline = Integer.parseInt(line);

//arr.insert(name,proclevel,procscore,procline);
//System.out.println("Before sorting:");
//arr.display(); // display items
//arr.insertionSort(); // insertion-sort them
//System.out.println("After sorting:");
arr.display(); // display them again
} // end main()
} // end class ObjectSortApp
////////////////////////////////////////////////////////////////
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
Using array is the worst possible option

with array you need to be limited by overall size
with array you don't have any opreations which wil, insert your element in the midlle and shift other elements - you have to write them youslef.
Actually arrays are very inconvenient (frankly I never use them wuith the exception when something is strictly static, like say arrayu of fields on the chessboard).

You definitely want to use collections/
TreeSet in this case is the simples and most straightforward; you can also do it with ArrayList
Myabe also with LinkedList, but that is more convoluted.
You defintely don;t want to use arrays
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
In this case in fact your main oeration is to have them ordered - and  this is the sopecial feature of TreeSet  - when you add element there - it alread adds it in the corerect position. That's why TreeSet is so convenient and appropriate in this case. LinkedList does not have this poroperty and will be almost the same as ArrayList in this case.
0
 
LVL 47

Assisted Solution

by:for_yan
for_yan earned 500 total points
Comment Utility
This is the implementation with LinkedList instead of
TreeSet
The difference is that when you add anew element - you need to use Collections.sort(list, comparator) method every time, rather than rely on automatic sorting in the treeSet

Luckily the same comparator class which I uesed to create the TreeSett can be used for sorting the list in case of LinkedList

LinkeList does not also have this convenient method last() which has a TreeSet - so I replaced it with the lement at the position size()-1 after sorting the LinkedList.

So this is the code with LinkedList:


import java.util.*;
import javax.swing.*;

class Link {
    public String dName; // data item
    public int dLevel, dScore, dLine;   //data item     
    public Link next; // next link in list

// -------------------------------------------------------------
public Link(String name, int level, int score, int line){ // constructor
    dName = name; 
    dLevel = level;
    dScore = score;
    dLine = line;
    }


// -------------------------------------------------------------
public void displayLink(){ // display ourself
    System.out.print(" Name: " + dName);
    System.out.print(", Level: " + dLevel);
    System.out.print(", Score: " + dScore);
    System.out.print(", Line: " + dLine);
    System.out.println ();
}
public int getScore(){
    return dScore;
}


} // end class Link
////////////////////////////////////////////////////////////////
class MyLinkComparator implements Comparator<Link>{

    public int compare(Link a1, Link a2){
                  if(a2.getScore() > a1.getScore())return 1;
        else if(a2.getScore() == a1.getScore())return 0;
        else return -1;
    }


}




class LinkList
{
private Link first; // ref to first item on list
// -------------------------------------------------------------

public LinkList() // constructor
{ first = null; } // no items on list yet
// -------------------------------------------------------------

public boolean isEmpty() // true if list is empty
{ return (first==null); }
// -------------------------------------------------------------
public void insertFirst(String name, int level, int score, int line) // insert at start of list
{ // make new link
Link newLink = new Link(name, level, score, line);
newLink.next = first; // newLink --> old first
first = newLink; // first --> newLink
}
// -------------------------------------------------------------
public Link deleteFirst() // delete first item
{ // (assumes list not empty)
Link temp = first; // save reference to link
first = first.next; // delete it: first-->old next
return temp; // return deleted link
}
// -------------------------------------------------------------
public void displayList()
{
Link current = first; // start at beginning of list
while(current != null) // until end of list,
{
current.displayLink(); // print data
current = current.next; // move to next link
}
System.out.println("");

}
// -------------------------------------------------------------
} // end class LinkList
////////////////////////////////////////////////////////////////
class LinkStack
{
private LinkedList<Link> theList;
//--------------------------------------------------------------
public LinkStack(LinkedList<Link> ts) // constructor
{
theList = ts;
}
//--------------------------------------------------------------
    /*
    public void push(String name, int level, int score, int line) // put item on top of stack
{
theList.insertFirst(name, level, score, line);
}
//--------------------------------------------------------------
public Link pop() // take item from top of stack
{
return theList.deleteFirst();
}
//--------------------------------------------------------------
public boolean isEmpty() // true if stack is empty
{
return ( theList.isEmpty() );
}
*/

//--------------------------------------------------------------
public void push(Link anew){
    theList.add(anew);
    Collections.sort(theList, new MyLinkComparator());
   theList.remove(theList.size()-1);
}



public void displayStack()
{
System.out.println(" Stack (top-->bottom): ");
//theList.displayList();
    for(Link a: theList){
        a.displayLink();
    }

}

class scoreInput {
    int dInput;
    
    public scoreInput(int input){
    dInput = input;
  //  If(dInput > score )
}
//--------------------------------------------------------------
} // end class LinkStack
}
////////////////////////////////////////////////////////////////
public class LinkStackApp
{
public static void main(String[] args)
{
LinkedList<Link> ts = new LinkedList<Link>();
    ts.add(new Link("Jazzy", 8, 25081, 211));


// make stack

 // push items
ts.add(new Link("Peter", 7, 24099, 202));
ts.add(new Link("Dave", 6,622188,199));
ts.add(new Link("Cindy", 5, 20765, 178));
ts.add(new Link("Jaskiret", 4 ,18882, 165));
ts.add(new Link("Robbie", 4, 17399, 145));
ts.add(new Link("Elton", 3, 14328, 134));
ts.add(new Link("Mel", 3, 12590, 125));
ts.add(new Link("Prince", 3, 9439, 102));
ts.add(new Link("Aaron", 2, 5628, 88));

    Collections.sort(ts, new MyLinkComparator());


    LinkStack theStack = new LinkStack(ts);

theStack.displayStack(); // display stack

String name = JOptionPane.showInputDialog(null,"Name :");
String level = JOptionPane.showInputDialog(null,"Level :");
int proclevel = Integer.parseInt(level);

String score = JOptionPane.showInputDialog(null,"Score :");
int procscore = Integer.parseInt(score);

String line = JOptionPane.showInputDialog(null,"Line :");
int procline = Integer.parseInt(line);

    Link anew = new Link(name, proclevel, procscore, procline);

    theStack.push(anew);



    theStack.displayStack();


} // end main()
} // end class LinkStackApp

Open in new window

0
 

Author Comment

by:swpui
Comment Utility
Let said I fixed only 10 people in the array,....each time whenever there is new score>existing score, then array will be able to implement, right? But how am I going to compare the score?
0
 
LVL 47

Assisted Solution

by:for_yan
for_yan earned 500 total points
Comment Utility
>Let said I fixed only 10 people in the array,....each time whenever there is new score>existing score, then array will be able to implement, right? But how am I going to compare the score?

what the code which I posed above does is it has a method which allows to order the list of Links (how you named them) by the score value

So the method which you named push() and I left the name but modified the contents does the following: first it adds the newly added Link to our LinkedList, then it uses this sorting method to sort the LinkedList - then it removes the last Link (the llInk with the minimum score).

So this method will ensure that we'll alwyas keep the same number of Links with which we started because in each call we add one Link and we remove one Link.
It will also ensure that if the new Link had a score higher than the minimal value in the existing list then this new Link will beciome not the last one upon sorting and will survive fin the list. If we happen to add the Link with the score less than minum in existing list tehn sorting will produce LiknkedList with the newly added Link at the very bottom and this Link will be removed - so the list as a results will not cahnge.

So the main thing is to make correct sorrting method which should compare using the scorwe value. to accomplish this we define class MyLinkComparator which implements Comparator<Link>  and compares Link instances based on the score value.
After we defined such class we can use instance of this class as the second parameter in the Collections.sort(...) method and it ensures that we order Link instances based on their score
0
 

Author Comment

by:swpui
Comment Utility
Yan, I am not saying the Linked list method, that one seems ok.
Now I am trying to fix the array consist of 10 people. I need to try with the array data structure so that I can have a comparison with linkedlist data structure.
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
You can fix 10 people with the LinkedList also.

You can do tthis also with the array - however create initially warray for 11 people and populate it with 10 people.

Then classs Arrays has simlar sortting method as class collections:

http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#sort%28T[],%20java.util.Comparator%29

So you can use the same comparator.

Then you'll assygn your new Link into 11th position (actulaly it will be index = 10, as of courese we start countng form 0) and then use Arrays.sort(array, comparator)
and then assign null to element with index 10.

So this will be very similar.

though there is no justification why to do it with array - much less conveneient
0
 
LVL 47

Assisted Solution

by:for_yan
for_yan earned 500 total points
Comment Utility
This is implementation with array:

import java.util.*;
import javax.swing.*;

class Link {
    public String dName; // data item
    public int dLevel, dScore, dLine;   //data item
    public Link next; // next link in list

// -------------------------------------------------------------
public Link(String name, int level, int score, int line){ // constructor
    dName = name;
    dLevel = level;
    dScore = score;
    dLine = line;
    }


// -------------------------------------------------------------
public void displayLink(){ // display ourself
    System.out.print(" Name: " + dName);
    System.out.print(", Level: " + dLevel);
    System.out.print(", Score: " + dScore);
    System.out.print(", Line: " + dLine);
    System.out.println ();
}
public int getScore(){
    return dScore;
}


} // end class Link
////////////////////////////////////////////////////////////////
class MyLinkComparator implements Comparator<Link>{

    public int compare(Link a1, Link a2){
        if(a1 == null && a2 == null)return 0;
        if(a1 == null)return 1;
        if(a2 == null)return -1;
                  if(a2.getScore() > a1.getScore())return 1;
        else if(a2.getScore() == a1.getScore())return 0;
        else return -1;
    }


}




class LinkList
{
private Link first; // ref to first item on list
// -------------------------------------------------------------

public LinkList() // constructor
{ first = null; } // no items on list yet
// -------------------------------------------------------------

public boolean isEmpty() // true if list is empty
{ return (first==null); }
// -------------------------------------------------------------
public void insertFirst(String name, int level, int score, int line) // insert at start of list
{ // make new link
Link newLink = new Link(name, level, score, line);
newLink.next = first; // newLink --> old first
first = newLink; // first --> newLink
}
// -------------------------------------------------------------
public Link deleteFirst() // delete first item
{ // (assumes list not empty)
Link temp = first; // save reference to link
first = first.next; // delete it: first-->old next
return temp; // return deleted link
}
// -------------------------------------------------------------
public void displayList()
{
Link current = first; // start at beginning of list
while(current != null) // until end of list,
{
current.displayLink(); // print data
current = current.next; // move to next link
}
System.out.println("");

}
// -------------------------------------------------------------
} // end class LinkList
////////////////////////////////////////////////////////////////
class LinkStack


{
    final static int NUM_PERS=10;
private Link[] theList;
//--------------------------------------------------------------
public LinkStack(Link[] ts) // constructor
{
theList = ts;
}
//--------------------------------------------------------------
    /*
    public void push(String name, int level, int score, int line) // put item on top of stack
{
theList.insertFirst(name, level, score, line);
}
//--------------------------------------------------------------
public Link pop() // take item from top of stack
{
return theList.deleteFirst();
}
//--------------------------------------------------------------
public boolean isEmpty() // true if stack is empty
{
return ( theList.isEmpty() );
}
*/

//--------------------------------------------------------------
public void push(Link anew){
    theList[NUM_PERS]=anew;
    Arrays.sort(theList, new MyLinkComparator());
   theList[NUM_PERS] = null;
}



public void displayStack()
{
System.out.println(" Stack (top-->bottom): ");
//theList.displayList();
    for(Link a: theList){
        if(a != null)
        a.displayLink();
    }

}

class scoreInput {
    int dInput;

    public scoreInput(int input){
    dInput = input;
  //  If(dInput > score )
}
//--------------------------------------------------------------
} // end class LinkStack
}
////////////////////////////////////////////////////////////////
public class LinkStackApp
{
public static void main(String[] args)
{
Link[] ts = new Link[LinkStack.NUM_PERS+1];
    ts[0]=new Link("Jazzy", 8, 25081, 211);


// make stack

 // push items
ts[1]=new Link("Peter", 7, 24099, 202);
ts[2]=new Link("Dave", 6,622188,199);
ts[3]=new Link("Cindy", 5, 20765, 178);
ts[4]=new Link("Jaskiret", 4 ,18882, 165);
ts[5]=new Link("Robbie", 4, 17399, 145);
ts[6]=new Link("Elton", 3, 14328, 134);
ts[7]=new Link("Mel", 3, 12590, 125);
ts[8]=new Link("Prince", 3, 9439, 102);
ts[10]=new Link("Aaron", 2, 5628, 88);

    Arrays.sort(ts, new MyLinkComparator());


    LinkStack theStack = new LinkStack(ts);

theStack.displayStack(); // display stack

String name = JOptionPane.showInputDialog(null,"Name :");
String level = JOptionPane.showInputDialog(null,"Level :");
int proclevel = Integer.parseInt(level);

String score = JOptionPane.showInputDialog(null,"Score :");
int procscore = Integer.parseInt(score);

String line = JOptionPane.showInputDialog(null,"Line :");
int procline = Integer.parseInt(line);

    Link anew = new Link(name, proclevel, procscore, procline);

    theStack.push(anew);



    theStack.displayStack();


} // end main()
} // end class LinkStackApp

Open in new window

0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 

Author Comment

by:swpui
Comment Utility
The implementation with array seems like you use back all the codes in the linked list page and just change a few methods......so this array is something array linkedlist and the previous one is stack linkedlist? Is this what you mean?
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
Yes, you change the repositoiry of your objects and adjust required mnethods. In particular say in array implementatioin I had among some other thing to modify compoarator to accoiunt for nul values, because in case of linkedlist or treeset we didn't need to have nuill eleemts, whereas with array impolenmentatioin it ois necessary to trake care of possibiloity of nuill values
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
Of course a lot of syntax with array looks different than when you store objects in linbkedlist or TreeSet
0
 

Author Comment

by:swpui
Comment Utility
Yan, I do not quite understand with the below 2:

For Array:
public int compare(Link a1, Link a2){
        if(a1 == null && a2 == null)return 0;
        if(a1 == null)return 1;
        if(a2 == null)return -1;
                  if(a2.getScore() > a1.getScore())return 1;
        else if(a2.getScore() == a1.getScore())return 0;
        else return -1;

For LinkedList:
class MyLinkComparator implements Comparator<Link>{

    public int compare(Link a1, Link a2){
        if(a2.getScore() > a1.getScore())return 1;
        else if(a2.getScore() == a1.getScore())return 0;
        else return -1;
    }
0
 
LVL 47

Assisted Solution

by:for_yan
for_yan earned 500 total points
Comment Utility
As i wrote above - when we deal with implementation using collections like LinkedList or TreeSet  we can arrange the code in such way that the collection which we are using never needs to contain null elemenets. Therefore implementation of method
int compare(Link a1, Link a2) can just ignore the cases when any one of the two elements is actually null.
Howevere in order tyo imeplement the logic with array, we need to create array which is one element bigger than we initially populate and sort it. Therefore in order to sort it using comparator we should make sure that out compare() method has the ability to hanlde situations where one of the compared objects is null
therefore whene I changed to array implemenetation - I had to change the implemenetation of the method compare() in Comparator class.
The method used for case with the array implementation can be usedf in those codes which usee linkedList as well; howevere if you use simple compare() method with arrays - you'll get error - so I needed to modify it to accommodate for null elements when switching to array implementation
0
 

Author Comment

by:swpui
Comment Utility
Last question to ask you, Yan:
As I had declared at the begining 'public Link(String name, int level, int score, int line)' and later you used 'public int compare(Link a1, Link a2)', how's u relate a1, a2 with the LINK()?
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
You created class Link

I created the class which implements Comparator for type Link, therefore
in this method:
public int compare(Link a1, Link a2) compares instances of the type Link which you creted and allows to establish for each pair of instances of class Link which one is "bigger" than the other; so this method is to comapre the instances of the class which you defined
0
 

Author Comment

by:swpui
Comment Utility
In the class Link, I declared name, level, score, line as well................
how the program knew a1, a2 are the scores to compare, how you relate them?
0
 
LVL 47

Accepted Solution

by:
for_yan earned 500 total points
Comment Utility
Look inside the compare method - you'll see that it comapres scores
like if(a2.getScore() > a1.getScore()) return 1;, etc.
This shows taht it establishes order based on the orderr of scores, and becuase a1, a2 are instances of Link, so they have method getScore() which returns score
0
 

Author Closing Comment

by:swpui
Comment Utility
Thanks Yan, I am clear now.
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now