Linked List: print contents
How can I print out the contents of a linked list whose nodes are made up of Data Objects?
If I do, "System.out.println("Node: " + detailsList);"
I get this kinda stuff:
[my.package.Switch@df6ccd, my.package.Pbx@601bb1, my.package.Switch@1ba34f2]
thanks
Override the toString() method in your data object.
Example:
public String toString() {
return name + " | " + ip + " | " + mac;
}
Similar Messages
-
How to print the contents of doubly-Linked List
Hi
I have a DLList consists of header , trailer and 10 linked nodes in between
Is there a simple way to print the contents ie "the elements"
of the list
thanksIn general you should write an iterator for every linked data structure for fast traversal. I'm guessing you're writing your own DLL for an assignment because one normally uses the LinkedList structure that is included in the api. Anyway, here is an example of how the iterator is implemented for a double linked list:
http://www.theparticle.com/_javadata2.html#Doubly_Linked_Lists_with_Enumeration -
Printing Linked List in reverse
Hi
Im trying to print a linked list in reverse order.. ive tried to put the objects into an array stack and then start printing form the top of the stack.
any ideas?You don't want to be making it more complicated with Queues or Stacks.
you can get a ListIterator from LinkedList
This Iterator not only has the next() method of normal Iterators, it also has a previous() method.
good enough hint? -
Creating a new WPC Content Layout for a Link List
Hello all,
As I've been lurking about the innards of Web Page Composer, I noticed that the Link List contains two different XSLTs for it representing different "Content Layouts".
Has anyone added a new Content Layout for an item? If so would they happen to have some high level steps on accomplishing it? It doesn't appear to be as difficult as some of the other custom configurations in adding new content types and new forms. So far I suspect the steps are:
Create the new XSLT and upload to KM.
Go to System Admin/System Configuration/KM/CM/Editor/Stylesheets/Stylesheets and hook up the XSLT to the engine
Go to System Admin/System Configuration/KM/CM/Editor/Stylesheets/Stylesheet Groups/Document Styles Groups and add the stylesheet to the lists group.
Bounce the Portal
That seems to be it, but it would shock me if it was all that was required.
Any thoughts?So I answered my own question.
It is as simple as I listed above. To create a new list rendering:
Simply create the new XSLT and stick it under /etc/wpceditor/styles
Then create the StyleSheet reference under: System Admin/System Configuration/KM/CM/Editor/Stylesheets/Stylesheets.
Then add the StyleSheet reference to the "lists" group.
Bounce the portal.
You'll have a new option when you select the style. -
Help with copying contents of file to link list please
Hi,
Below is a snippet of code I am playing with. As you can see I have created a LinkList, I now need to copy the contents of a csv file in to that list. The file is several lines long and I need each line in the list.
I know how to add to the list manually i.e.,
list.add("First entry in list");
Could someone help me out with this please.
Many thanks.
(***CODE***)
private LinkedList list = new LinkedList();
public LinkTest()
// ** List content START **
// Open the file today.csv
File inFile = new File("C:\\today.csv");
// Create a file stream, wrapping the file
FileReader fileReader = new FileReader(inFile);
// Create a second wrapper,
BufferedReader bufReader = new BufferedReader(fileReader);
// Read in the first line...
String s;
s = bufReader.readLine();
list.add(s);
StringTokenizer st = new StringTokenizer(s);
while (st.hasMoreTokens())
System.out.println(st.nextToken());
// ** List content END **
I looked at your code and I thought, what's the question for, it's already adding lines to the list. And then I looked again and had the same thought. The third time I looked I noticed you didn't code the loop that read all the lines from the file. Silly me, I thought your question had something to do with linked lists.
Anyway, to answer your real question, which is how do you read all the lines from a text file:while ((s = bufReader.readLine()) != null) {
// do something with the String s here
// such as adding it to a linked list
} -
Help - can't print linked list object
Hi all,
I've written a program that creates an Airplane object. I've added the Airplane object to a linked list. I am trying to test by printing the linked list..but I get the addresses of the airplane object instead of the integer variables that the Airplane object contains. How can I fix this? Here's my output showing what I am talking about:
Airplane type: 2
Airplane arrival time: 600
Airplane cleaning time: 45
Airplane take-off time: 645
[Airplane@665753]
Airplane type: 3
Airplane arrival time: 1100
Airplane cleaning time: 60
Airplane take-off time: 1160
[Airplane@665753, Airplane@ef22f8]
Airplane type: 1
Airplane arrival time: 900
Airplane cleaning time: 30
Airplane take-off time: 930
[Airplane@665753, Airplane@ef22f8, Airplane@e0cf70]
Airplane type: 1
Airplane arrival time: 1100
Airplane cleaning time: 30
Airplane take-off time: 1130
[Airplane@665753, Airplane@ef22f8, Airplane@e0cf70, Airplane@52fe85]
Airplane type: 3
Airplane arrival time: 1000
Airplane cleaning time: 60
Airplane take-off time: 1060
[Airplane@665753, Airplane@ef22f8, Airplane@e0cf70, Airplane@52fe85, Airplane@c40c80]
Airplane type: 2
Airplane arrival time: 900
Airplane cleaning time: 45
Airplane take-off time: 945
[Airplane@665753, Airplane@ef22f8, Airplane@e0cf70, Airplane@52fe85, Airplane@c40c80, Airplane@10d81b]
Airplane type: 2
Airplane arrival time: 900
Airplane cleaning time: 45
Airplane take-off time: 945
[Airplane@665753, Airplane@ef22f8, Airplane@e0cf70, Airplane@52fe85, Airplane@c40c80, Airplane@10d81b, Airplane@dbe178]
Airplane type: 3
Airplane arrival time: 1000
Airplane cleaning time: 60
Airplane take-off time: 1060
[Airplane@665753, Airplane@ef22f8, Airplane@e0cf70, Airplane@52fe85, Airplane@c40c80, Airplane@10d81b, Airplane@dbe178, Airplane@af9e22]
Airplane type: 1
Airplane arrival time: 900
Airplane cleaning time: 30
Airplane take-off time: 930
[Airplane@665753, Airplane@ef22f8, Airplane@e0cf70, Airplane@52fe85, Airplane@c40c80, Airplane@10d81b, Airplane@dbe178, Airplane@af9e22, Airplane@b6ece5]
Airplane type: 1
Airplane arrival time: 700
Airplane cleaning time: 30
Airplane take-off time: 730
[Airplane@665753, Airplane@ef22f8, Airplane@e0cf70, Airplane@52fe85, Airplane@c40c80, Airplane@10d81b, Airplane@dbe178, Airplane@af9e22, Airplane@b6ece5, Airplane@7ace8d]
Airplane@665753
import java.io.*;
import java.util.*;
public class AirPortSimulator {
public static void main(String[] args) {
LinkedList<Airplane> myEventList = new LinkedList();
//for loop to test random number generator for airplane type
for( int i = 0; i < 10; i++){
int parOne = myNumber();
System.out.println("Airplane type: " + parOne);
int parTwo = myTime();
System.out.println("Airplane arrival time: " + parTwo);
int parThree = 0;
switch(parOne){
case 1: parThree = 30;break;
case 2: parThree = 45;break;
case 3: parThree = 60;break;
System.out.println("Airplane cleaning time: " + parThree);
int parFour=0;
switch(parOne){
case 1: parFour = parTwo + 30;break;
case 2: parFour = parTwo + 45;break;
case 3: parFour = parTwo + 60;break;
System.out.println("Airplane take-off time: " + parFour);
System.out.println();
Airplane myAirplane = new Airplane(parOne, parTwo, parThree, parFour);
myEventList.addLast(myAirplane);
System.out.println(myEventList);
System.out.println();
public static int myTime(){
Random generator = new Random();
int number = generator.nextInt(16)+1;
number = number * 100;
if (number < 600){
number = number + 600;
return number;
public static int myNumber(){
Random generator = new Random();
return generator.nextInt(3)+1;
}I've written a method before that prints all the
elements of a linked list..but that method onlyheld
one integer or string...it was a "while (head !=
null) loop that traversed the list and printed
"head.info"
But i'm confused with an object that has 4integers
inside it...You don't have to write any kind of loop. The
LinkedList implementation of toString does that for
you. All you have to do is write a toString for
Airplane that prints whatever you feel is important
for a single Airplane object.
But note that since the list uses commas to separate
entries, your toString method will be clearer if you
can write it in such a way that it doesn't use
commas, or so that you can see where the output
begins and ends. For example, maybe you can wrap the
output with curly brackets.Thanks, I just had to understand what the toString method was and then how to override it. This works well:
Thank you for pointing me in the right direction.
aiki985
public String toString(){
return "{" + airplaneType + ", " + arrivalTime + ", " +
waitingTime + ", " + departureTime + "}";
} // end toString method -
Need help regarding Linked List
I'm a beginner who just spent ages working on the following code.. but need help on re-implementing the following using a linked list, i.e. no array is allowed for customer records but you still can use arrays for names, address, etc.. Hopefully I've inserted enough comments..
Help very much appreciated!! Thanks! =]
import java.util.Scanner;
import java.io.*;
public class Bank
/* Private variables declared so that the data is only accessible to its own
class, but not to any other class, thus preventing other classes from
referring to the data directly */
private static Customer[] customerList = new Customer[30];
//Array of 30 objects created for storing information of each customer
private static int noOfCustomers;
//Integer used to store number of customers in customerList
public static void main(String[] args)
Scanner sc = new Scanner(System.in);
menu();
public static void menu()
char choice;
String filename;
int custId,counter=0;
double interestRate;
Scanner sc = new Scanner(System.in);
do
//Displaying of Program Menu for user to choose
System.out.println("ABC Bank Customer Management System Menu");
System.out.println("========================================");
System.out.println("(1) Input Data from File");
System.out.println("(2) Display Data");
System.out.println("(3) Output Data to File");
System.out.println("(4) Delete Record");
System.out.println("(5) Update Record");
System.out.println("(Q) Quit");
System.out.println();
System.out.print("Enter your choice: ");
String input = sc.next();
System.out.println();
choice = input.charAt(0);
//switch statement used to assign each 'selection' to its 'operation'
switch(choice)
case '1': int noOfRecords;
System.out.print("Enter file name: ");
sc.nextLine();
filename = sc.nextLine();
System.out.println();
noOfRecords = readFile(filename);
System.out.println(+noOfRecords+" records read.");
break;
case '2': displayRecords();
break;
case '3': writeFile();
break;
case '4': System.out.print("Enter account ID to be deleted: ");
sc.nextLine();
custId = sc.nextInt();
deleteRecord(custId);
break;
case '5': if(counter==0)
System.out.print("Enter current interest rate for saving account: ");
sc.nextLine();
interestRate = sc.nextDouble();
update(interestRate);
counter++;
else
System.out.println("Error: Accounts have been updated for the month.");
break;
}System.out.println();
}while(choice!='Q' && choice!='q');
/* The method readFile() loads the customer list of a Bank from a specified
text file fileName into customerList to be stored as array of Customer
objects in customerList in ascending alphabetical order according to the
customer names */
public static int readFile(String fileName)
int custId,i=0;
String custName,custAddress,custBirthdate,custPhone,custAccType;
double custBalance,curRate;
boolean d;
/* Try block to enclose statements that might throw an exception, followed by
the catch block to handle the exception */
try
Scanner sc = new Scanner(new File(fileName));
while(sc.hasNext())
/* sc.next() gets rid of "Account", "Id" and "=" */
sc.next();sc.next();sc.next();
custId = sc.nextInt();
d=checkDuplicate(custId);
/* checkDuplicate() is a method created to locate duplicating ids in array */
if(d==true)
/* A return value of true indicates duplicating record and the sc.nextLine()
will get rid of all the following lines to read the next customer's record */
sc.nextLine();sc.nextLine();sc.nextLine();
sc.nextLine();sc.nextLine();sc.nextLine();
continue;
/* A return value of false indicates no duplicating record and the following
lines containing the information of that customer's record is being read
in */
if(d==false)
/* sc.next() gets rid of "Name" and "=" and name is changed to upper case*/
sc.next();sc.next();
custName = sc.nextLine().toUpperCase();
/* sc.nextLine get rids of the following lines to read the next customer's
record if length of name is more than 20 characters*/
if(custName.length()>21)
System.out.println("Name of custId "+custId+" is more than 20 characters");
System.out.println();
sc.nextLine();sc.nextLine();sc.nextLine();sc.nextLine();
continue;
/* sc.next() gets rid of "Address" and "=" */
sc.next();sc.next();
custAddress = sc.nextLine();
/* sc.nextLine get rids of the following lines to read the next customer's
record if length of address is more than 80 characters*/
if(custAddress.length()>81)
System.out.println("Address of custId "+custId+" is more than 80 characters");
System.out.println();
sc.nextLine();sc.nextLine();sc.nextLine();sc.nextLine();
continue;
/* sc.next() gets rid of "DOB" and "=" */
sc.next();sc.next();
custBirthdate = sc.nextLine();
/* sc.nextLine get rids of the following lines to read the next customer's
record if length of date of birth is more than 10 characters*/
if(custBirthdate.length()>11)
System.out.println("D.O.B of custId "+custId+" is more than 10 characters");
System.out.println();
sc.nextLine();sc.nextLine();sc.nextLine();sc.nextLine();
continue;
/* sc.next() gets rid of "Phone", "Number" and "=" */
sc.next();sc.next();sc.next();
custPhone = sc.nextLine();
/* sc.nextLine get rids of the following lines to read the next customer's
record if length of phone number is more than 8 characters*/
if(custPhone.length()>9)
System.out.println("Phone no. of custId "+custId+" is more than 8 characters");
System.out.println();
sc.nextLine();sc.nextLine();sc.nextLine();sc.nextLine();
continue;
/* sc.next() gets rid of "Account", "Balance" and "=" */
sc.next();sc.next();sc.next();
custBalance = sc.nextDouble();
/* sc.next() gets rid of "Account", "Type" and "=" */
sc.next();sc.next();sc.next();
custAccType = sc.next();
if(custAccType.equals("Saving"))
customerList[noOfCustomers] = new Account1(custId,custName,custAddress,custBirthdate,custPhone,custBalance,custAccType);
sc.nextLine();
noOfCustomers++;
i++;
else if(custAccType.equals("Checking"))
customerList[noOfCustomers] = new Account2(custId,custName,custAddress,custBirthdate,custPhone,custBalance,custAccType);
sc.nextLine();
noOfCustomers++;
i++;
else if(custAccType.equals("Fixed"))
sc.next();sc.next();sc.next();sc.next();
curRate = sc.nextDouble();
Account3 temp = new Account3(custId,custName,custAddress,custBirthdate,custPhone,custBalance,custAccType,curRate);
customerList[noOfCustomers]=temp;
sc.nextLine();
noOfCustomers++;
i++;
else
System.out.println("Account type not defined.");
if(noOfCustomers==30)
System.out.println("The customer list has reached its maximum limit of 30 records!");
System.out.println();
return noOfCustomers;
//Exceptions to be caught
catch (FileNotFoundException e)
System.out.println("Error opening file");
System.exit(0);
catch (IOException e)
System.out.println("IO error!");
System.exit(0);
/* Bubblesort method used to sort the array in ascending alphabetical order
according to customer's name */
bubbleSort(customerList);
return i;
/* The method displayRecords() displays the data of the customer records on
screen */
public static void displayRecords()
int k;
/* Displaying text using the printf() method */
for(k=0;k<noOfCustomers;k++)
System.out.printf("Name = %s\n", customerList[k].getName());
System.out.printf("Account Balance = %.2f\n", customerList[k].getBalance());
System.out.printf("Account Id = %d\n", customerList[k].getId());
System.out.printf("Address = %s\n", customerList[k].getAddress());
System.out.printf("DOB = %s\n", customerList[k].getBirthdate());
System.out.printf("Phone Number = %s\n", customerList[k].getPhone());
String type = customerList[k].getAccType();
System.out.println("Account Type = " +type);
if(type.equals("Fixed"))
System.out.println("Fixed daily interest = "+((Account3)customerList[k]).getFixed());
System.out.println();
/* The method writeFile() saves the content from customerList into a
specified text file. Data is printed on the screen at the same time */
public static void writeFile()
/* Try block to enclose statements that might throw an exception, followed by
the catch block to handle the exception */
try
int i;
int n=0;
//PrintWriter class used to write contents of studentList to specified file
FileWriter fwStream = new FileWriter("newCustomers.txt");
BufferedWriter bwStream = new BufferedWriter(fwStream);
PrintWriter pwStream = new PrintWriter(bwStream);
for(i=0;i<noOfCustomers;i++)
pwStream.println("Account Id = "+customerList.getId());
pwStream.println("Name = "+customerList[i].getName());
pwStream.println("Address = "+customerList[i].getAddress());
pwStream.println("DOB = "+customerList[i].getBirthdate());
pwStream.println("Phone Number = "+customerList[i].getPhone());
pwStream.printf("Account Balance = %.2f\n", customerList[i].getBalance());
pwStream.println("Account Type = "+customerList[i].getAccType());
if(customerList[i].getAccType().equals("Fixed"))
pwStream.println("Fixed Daily Interest = "+((Account3)customerList[i]).getFixed());
pwStream.println();
n++;
//Closure of stream
pwStream.close();
System.out.println(+n+" records written.");
catch(IOException e)
System.out.println("IO error!");
System.exit(0);
//Deletes specified record from list
public static void deleteRecord(int id)
int i;
i=locate(id);
if(i==200)
//checking if account to be deleted does not exist
System.out.println("Error: no account with the id of "+id+" found!");
//if account exists
else
while(i<noOfCustomers)
customerList[i] = customerList[i+1];
i++;
System.out.println("Account Id: "+id+" has been deleted");
--noOfCustomers;
//Updates the accounts
public static void update(double interest)
int i,j,k;
double custBalance,addition=0;
for(i=0;i<noOfCustomers;i++)
if(customerList[i] instanceof Account1)
for(j=0;j<30;j++)
addition=customerList[i].getBalance()*interest;
custBalance=customerList[i].getBalance()+addition;
customerList[i].setBalance(custBalance);
else if(customerList[i] instanceof Account2)
continue;
else if(customerList[i] instanceof Account3)
for(j=0;j<30;j++)
addition=customerList[i].getBalance()*((Account3)customerList[i]).getFixed();
custBalance=customerList[i].getBalance()+addition;
customerList[i].setBalance(custBalance);
else
System.out.println("Account type not defined");
System.out.println("The updated balances are: \n");
for(k=0;k<noOfCustomers;k++)
System.out.printf("Name = %s\n", customerList[k].getName());
System.out.printf("Account Balance = %.2f\n", customerList[k].getBalance());
System.out.println();
/* ================== Additional methods ==================== */
/* Bubblesort method to sort the customerList in ascending alphabetical
order according to customer's name */
public static void bubbleSort(Customer[] x)
int pass, index;
Customer tempValue;
for(pass=0; pass<noOfCustomers-1; pass++)
for(index=0; index<noOfCustomers-1; index++)
if(customerList[index].getName().compareToIgnoreCase(customerList[index+1].getName()) > 0)
tempValue = x[index];
x[index] = x[index+1];
x[index+1]= tempValue;
/* Method used to check for duplicated ids in array */
public static boolean checkDuplicate(int id)
int i;
for(i=0;i<noOfCustomers;i++)
if(id == customerList[i].getId())
System.out.println("Account Id = "+id+" already exists");
System.out.println();
return true;
}return false;
/* Method to seach for account id in array */
public static int locate(int id)
int j;
for(j=0;j<noOfCustomers;j++)
if(customerList[j].getId()==id)
return j;
j=200;
return j;
import java.util.Scanner;
public class Customer
/* The following private variables are declared so that the data is only
accessible to its own class,but not to any other class, thus preventing
other classes from referring to the data directly */
protected int id;
protected String name,address,birthdate,phone,accType;
protected double balance;
// Null constructor of Customer
public Customer()
id = 0;
name = null;
address = null;
birthdate = null;
phone = null;
balance = 0;
accType = null;
/* The following statements with the keyword this activates the Customer
(int id, String name String address, String birthdate, String phone, double
balance) constructor that has six parameters of account id, name, address,
date of birth, phone number, account balance and assign the values of the
parameters to the instance variables of the object */
public Customer(int id, String name, String address, String birthdate, String phone, double balance, String accType)
//this is the object reference that stores the receiver object
this.id = id;
this.name = name;
this.address = address;
this.birthdate = birthdate;
this.phone = phone;
this.balance = balance;
this.accType = accType;
/* The following get methods getId(), getName(), getAddress(), getBirthdate(),
getPhone(), getBalance() return the values of the corresponding instance
properties */
public int getId()
return id;
public String getName()
return name;
public String getAddress()
return address;
public String getBirthdate()
return birthdate;
public String getPhone()
return phone;
public double getBalance()
return balance;
public String getAccType()
return accType;
/* The following set methods setId(), setName(), setAddress(), setBirthdate(),
setPhone and setBalance() set the values of the corresponding instance
properties */
public void setId (int custId)
id = custId;
public void setName(String custName)
name = custName;
public void setAddress (String custAddress)
address = custAddress;
public void setBirthdate (String custBirthdate)
birthdate = custBirthdate;
public void setPhone (String custPhone)
phone = custPhone;
public void setBalance (double custBalance)
balance = custBalance;
public void setAccType (String custAccType)
accType = custAccType;
class Account1 extends Customer
public Account1(int id, String name, String address, String birthdate, String phone, double balance, String accType)
super(id,name,address,birthdate,phone,balance,accType);
this.id = id;
this.name = name;
this.address = address;
this.birthdate = birthdate;
this.phone = phone;
this.balance = balance;
this.accType = accType;
class Account2 extends Customer
public Account2(int id, String name, String address, String birthdate, String phone, double balance, String accType)
super(id,name,address,birthdate,phone,balance,accType);
this.id = id;
this.name = name;
this.address = address;
this.birthdate = birthdate;
this.phone = phone;
this.balance = balance;
this.accType = accType;
class Account3 extends Customer
protected double fixed=0;
public Account3(int id, String name, String address, String birthdate, String phone, double balance, String accType, double fixed)
super(id,name,address,birthdate,phone,balance,accType);
this.id = id;
this.name = name;
this.address = address;
this.birthdate = birthdate;
this.phone = phone;
this.balance = balance;
this.accType = accType;
this.fixed = fixed;
public double getFixed()
return fixed;
Example of a customers.txt
Account Id = 123
Name = Matt Damon
Address = 465 Ripley Boulevard, Oscar Mansion, Singapore 7666322
DOB = 10-10-1970
Phone Number = 790-3233
Account Balance = 405600.00
Account Type = Fixed
Fixed Daily Interest = 0.05
Account Id = 126
Name = Ben Affleck
Address = 200 Hunting Street, Singapore 784563
DOB = 25-10-1968
Phone Number = 432-4579
Account Balance = 530045.00
Account Type = Saving
Account Id = 65
Name = Salma Hayek
Address = 45 Mexican Boulevard, Hotel California, Singapore 467822
DOB = 06-04-73
Phone Number = 790-0000
Account Balance = 2345.00
Account Type = Checking
Account Id = 78
Name = Phua Chu Kang
Address = 50 PCK Avenue, Singapore 639798
DOB = 11-08-64
Phone Number = 345-6780
Account Balance = 0.00
Account Type = Checking
Account Id = 234
Name = Zoe Tay
Address = 100 Blue Eyed St, Singapore 456872
DOB = 15-02-68
Phone Number = 456-1234
Account Balance = 600.00
Account Type = Saving1) When you post code, please use[code] and [/code] tags as described in Formatting tips on the message entry page. It makes it much easier to read.
2) Don't just post a huge pile of code and ask, "How do I make this work?" Ask a specific question, and post just enough code to demonstrate the problem you're having.
3) Don't just write a huge pile of code and then test it. Write a tiny piece, test it. Then write the piece that will work with or use the first piece. Test that by itself--without the first piece. Then put the two together and test that. Only move on to the next step after the current step produces the correct results. Continue this process until you have a complete, working program. -
Help needed in linked lists...
I have been working on this computer assignment lately but I still don't understand linked lists yet..I did an assignment on array based implementation and now I am supposed to do the same thing in linked list implementation..
I need help on how to change this into a linked list implementation..any help would be appreciated. Thank you..below is the code for the array based implementation..the only thing that needs change here is after where is says Array-based implementation of the ADT list.
public class ListArrayBasedDriver {
public static void main(String [] args) {
ListArrayBased myGroceryList = new ListArrayBased();
myGroceryList.add(1,"milk");
myGroceryList.add(2,"eggs");
myGroceryList.add(3,"butter");
myGroceryList.add(4,"pecans");
myGroceryList.add(5,"apples");
myGroceryList.add(6,"bread");
myGroceryList.add(7,"chicken");
myGroceryList.add(8,"rice");
myGroceryList.add(9,"red beans");
myGroceryList.add(10,"sausage");
myGroceryList.add(11,"flour");
printList(myGroceryList); //print out original List
System.out.print("numItems is now: " + myGroceryList.size() + "\n");
System.out.println("adding juice for 5th item...");
myGroceryList.add (5, (Object) "juice"); //add juice
System.out.println("item 5 is: " + myGroceryList.get(5)); //get position 5
printList(myGroceryList);
System.out.print("numItems is now: " + myGroceryList.size() + "\n");
System.out.println("removing juice...");
myGroceryList.remove (5); //remove item at position 5
printList(myGroceryList);
System.out.print("numItems is now: " + myGroceryList.size() + "\n");
public static void printList(ListArrayBased myList)
//method prints a list, numbering the values, e.g, "1. milk" .... "5. juice".... etc.
int i;
for(i=1; i <= myList.size(); i++)
String tempString = new String((String)myList.get(i));
System.out.println(i+" "+ tempString);
// Array-based implementation of the ADT list.
class ListArrayBased {
private static final int MAX_LIST = 50;
private Object items[]; // an array of list items
private int numItems; // number of items in list
public ListArrayBased()
// creates an empty list
items = new Object[MAX_LIST];
numItems = 0;
} // end default constructor
public boolean isEmpty()
return (numItems == 0);
} // end isEmpty
public int size()
return numItems;
} // end size
public void removeAll()
// Creates a new array; marks old array for
// garbage collection.
items = new Object[MAX_LIST];
numItems = 0;
} // end removeAll
public void add(int index, Object item) throws ListIndexOutOfBoundsException
if (numItems > MAX_LIST)
throw new ListException("ListException on add");
} // end if
if (index >= 1 && index <= numItems+1)
// make room for new element by shifting all items at
// positions >= index toward the end of the
// list (no shift if index == numItems+1)
for (int pos = numItems; pos >= index; pos--) {
items[translate(pos+1)] = items[translate(pos)];
} // end for
// insert new item
items[translate(index)] = item;
numItems++;
else
{ // index out of range
throw new ListIndexOutOfBoundsException(
"ListIndexOutOfBoundsException on add");
} // end if
} //end add
public Object get(int index) throws ListIndexOutOfBoundsException
if (index >= 1 && index <= numItems)
return items[translate(index)];
else
{ // index out of range
throw new ListIndexOutOfBoundsException(
"ListIndexOutOfBoundsException on get");
} // end if
} // end get
public void remove(int index) throws ListIndexOutOfBoundsException
if (index >= 1 && index <= numItems)
// delete item by shifting all items at
// positions > index toward the beginning of the list
// (no shift if index == size)
for (int pos = index+1; pos <= size(); pos++) {
items[translate(pos-1)] = items[translate(pos)];
} // end for
numItems--;
else
{ // index out of range
throw new ListIndexOutOfBoundsException("ListIndexOutOfBoundsException on remove");
} // end if
} // end remove
private int translate(int position) {
return position - 1;
} // end translate
} // end ListArrayBased
class ListException extends RuntimeException
public ListException(String s)
super(s);
} // end constructor
} // end ListException
class ListIndexOutOfBoundsException
extends IndexOutOfBoundsException {
public ListIndexOutOfBoundsException(String s) {
super(s);
} // end constructor
} // end ListIndexOutOfBoundsExceptionCould someone check for me if this will work and if it doesn't what I need to do to make it work..Thanks...
public class ListArrayBasedDriver {
public static void main(String [] args) {
ListArrayBased myGroceryList = new ListArrayBased();
myGroceryList.add(1,"milk");
myGroceryList.add(2,"eggs");
myGroceryList.add(3,"butter");
myGroceryList.add(4,"pecans");
myGroceryList.add(5,"apples");
myGroceryList.add(6,"bread");
myGroceryList.add(7,"chicken");
myGroceryList.add(8,"rice");
myGroceryList.add(9,"red beans");
myGroceryList.add(10,"sausage");
myGroceryList.add(11,"flour");
printList(myGroceryList); //print out original List
System.out.print("numItems is now: " + myGroceryList.size() + "\n");
System.out.println("adding juice for 5th item...");
myGroceryList.add (5, (Object) "juice"); //add juice
System.out.println("item 5 is: " + myGroceryList.get(5)); //get position 5
printList(myGroceryList);
System.out.print("numItems is now: " + myGroceryList.size() + "\n");
System.out.println("removing juice...");
myGroceryList.remove (5); //remove item at position 5
printList(myGroceryList);
System.out.print("numItems is now: " + myGroceryList.size() + "\n");
public static void printList(ListArrayBased myList)
//method prints a list, numbering the values, e.g, "1. milk" .... "5. juice".... etc.
int i;
for(i=1; i <= myList.size(); i++)
String tempString = new String((String)myList.get(i));
System.out.println(i+" "+ tempString);
// Linked List-based implementation of the ADT list.
class ListNode
//class to represent one node in a list
class ListNode
//package access members; List can access these directly
Object data;
ListNode nextNode;
//contructor creates a ListNode that refers to object
ListNode( Object object)
this( object, null );
} //end ListNode one-argument constructor
//constructor creates ListNode that refers to
// Object and to the next ListNode
ListNode ( Object object, ListNode node)
data = object;
nextNode = node;
// end ListNode two-argument contructor
//return reference to data in node
Object getObject()
return data; // return Object in this mode
//return reference to next node in list
ListNode getNext()
return nextNode; // get next node
} // end method getNext
} //end class ListNode
//class List Definition
public class List
private ListNode firstNode;
private ListNode lastNode;
private String name; // string like " list " used in printing
//contructor creates empty List with " list " as the name
public List()
this(" list ");
} //end List no-arguement constructor
//contructor creates an empty list with a name
public List( String listName )
name = listname;
firstNode = lastNode = null;
} //end List no-arguement contructor
//insert Object at front of List
public void insertAtFront ( object insertItem )
if ( isEmpty() ) //firstNode and lastNode refer to same object
firstNode = lastNode = newListNode( insertItem );
else // firstNode refers to new node
firstNode = new ListNode ( insertItem, firstNode );
} // end method insertAtFront
// insert Object at end of List
public void insert AtBack ( Object insertItem )
if ( isEmpty() ) //firstNode and lastNode refer to same object
firstNode = new ListNode ( insertItem );
else // firstNode refers to new node
firstNode = new ListNode (insertItem, firstNode );
} // end method insertAtFront
// insert Object at end of List
public void insertAtBack ( Object insertItem )
if ( isEmpty() ) //firstNode and LastNode refer to same Object
firstNode = lastNode = new ListNode ( insertItem );
else // lastNode = lastNode.nextNode = new ListNode ( insertItem );
} // end method insertAtBack
//remove first node from List
public Object removeFromFront() throws EmptyListException
if( isEmpty() ) //throw exception if list is empty
throw new EmptyListException( name );
object removedItem = firstNode.data; //retrieve data being removed
// update references firstNode and lastNode
if (firstNode == lastNode )
firstNode =lastNode = null;
else
firstNode = firstNode.nextNode;
return removedItem; // return removed node data
} //end method removeFromFront
//remove last node from List
Public Object removeFromBack() throws EmptyListException
If ( isEmpty() ) // throw exception if list is empty
throw new EmptyListException( name );
Object removedItem = lastNode.data; // retrieve data being removed
// update references firstNode and lastNode
If ( firstNode == lastNode )
firstNode = lastNode = null;
else // locate new last node
ListNode current = firstNode;
// loop while current node does not refer to lastNode
while ( current.nextNode != lastNode )
current = current.nextNode;
lastNode = current; // current is new lastNode
current.nextNode = null;
} // end else
return removedItem; // return removed node data
} // end method removeFromBack
// determine whether list is empty
public boolean isEmpty()
return firstNode == null; // return true if list is empty
} // end method isEmpty
//output List contents
public void print()
if (isEmpty() )
System.out.printf(�Empty %s\n�, name );
return;
System.out.printf(�The %s is: �, name );
ListNode current = firstNode;
//while (current != null )
System.out,printf(�%s �, current.data );
current = current.nextNode;
} //end while
System.out.println( �\n� );
} //end method print
} end class List -
Alphabetically ordering a Linked List
Would anyone please be able to give me help in ordering a linked list alphabetically. I'm new to java so please be gentle.
Many thanks in advance.I've just tried that but it gave me errors on trying to compile it:
.\List.java:91: Incompatible type for method. Explicit cast needed to convert List to java.util.List.
Collections.sort(leftList);
^
.\List.java:92: Incompatible type for method. Explicit cast needed to convert List to java.util.List.
Collections.sort(rightList);
^
2 errors
I'll post my coding below to see if you can help me out. Thanks a lot.
import java.util.LinkedList;
import java.util.Collections;
class ListNode {
// package access data so class List can access it directly
char data;
ListNode next;
// Constructor: Create a ListNode that refers to Object o.
ListNode( char c ) { this( c, null ); }
// Constructor: Create a ListNode that refers to Object o and
// to the next ListNode in the List.
ListNode( char c, ListNode nextNode )
data = c; // this node refers to Object o
next = nextNode; // set next to refer to next
// Return a reference to the Object in this node
char getChar() { return data; }
// Return the next node
ListNode getNext() { return next; }
// Class List definition
public class List {
private ListNode firstNode, current;
private ListNode lastNode;
private String name; // String like "list" used in printing
// Constructor: Construct an empty List with s as the name
public List( String s )
name = s;
firstNode = lastNode = null;
// Constructor: Construct an empty List with
// "list" as the name
public List() { this( "list" ); }
public synchronized boolean isEmpty()
{ return firstNode == null; }
public synchronized void insertAtBack( char insertItem )
if ( isEmpty() )
firstNode = lastNode = new ListNode( insertItem );
else
lastNode = lastNode.next = new ListNode( insertItem );
print();
// System.out.println(insertItem);
// public char getText(){
// return current.data;
// Output the List contents
public synchronized void print()
current = firstNode;
while ( current != null ) {
System.out.print(current.data);
current = current.next;
System.out.println( "\n" );
// method to split the linked list
public synchronized void splitList(){
System.out.println("splitList");
ListNode present = firstNode;
List leftList = new List(); // create the left list
List rightList = new List(); // create the right list
try{
while (present != null) {
leftList.insertAtBack(present.data);
System.out.println("left " +present.data);
present = present.next; // skips 1 node
rightList.insertAtBack(present.data);
System.out.println("right " +present.data);
present = present.next; // skips 1 node
Collections.sort(leftList);
Collections.sort(rightList);
catch(NullPointerException e){ -
Putting a class of objects in a Linked List?
Hi,
I copied a program from a book and I want to edit it and put studentRecord class in the Linked List. I've tried to play about with datum, but everything I try doesn't work. Can someone help me out? How could I put studentRecord in the LinkedList?
import java.io.*;
class IO
static BufferedReader keyboard = new
BufferedReader(new InputStreamReader(System.in));
static PrintWriter screen = new PrintWriter(System.out, true);
class studentRecord
private String name;
private int IDNumber;
class LinkedList
class Node
protected Object datum;
protected Node link;
public Node() {}
public Node(Object item, Node pointer)
datum = item;
link = pointer;
private Node head;
private Node tail;
private Node temporary;
private int nodeCount = 0;
//constructor
public LinkedList()
head = null;
tail = null;
temporary = null;
//method to insert an object into the linked list
public void insert(Object datum)
if (head == null) // list empty
head = new Node(datum, head);
tail = head;
else
temporary = new Node(datum, temporary);
tail.link = temporary;
tail = temporary;
temporary = null;
nodeCount++;
Full program can be found: http://dil3mma.tripod.com/LinkedList.txt
Thanks in advance.Hi jverd,
Thanks for replying. I've tried to change the program liked you said but there is 1 error I can't seem to fix(Im sure there are more tho). The error is "cannot resolve symbol" I typed in caps the line it happens on so it's easy to see. Any idea what it could be? Is it cause I'm comparing a String with Object?
import java.io.*;
class IO
static BufferedReader keyboard = new
BufferedReader(new InputStreamReader(System.in));
static PrintWriter screen = new PrintWriter(System.out, true);
class sRecord
private String name;
private int IDNumber;
class LinkedList
class Node
protected sRecord datum;
protected Node link;
public Node() {}
public Node(sRecord item, Node pointer)
datum = item;
link = pointer;
private Node head;
private Node tail;
private Node temporary;
private int nodeCount = 0;
//constructor
public LinkedList()
head = null;
tail = null;
temporary = null;
//method to insert an object into the linked list
public void insert(sRecord datum)
if (head == null) // list empty
head = new Node(datum, head);
tail = head;
else
temporary = new Node(datum, temporary);
tail.link = temporary;
tail = temporary;
temporary = null;
nodeCount++;
//method to delete an object from the linked list
public boolean delete(Object scrap)
Node previous = head;
//for every node in the linked list
for (Node current = head; current != null; current = current.link)
//node to be deleted is at the head of the list
if (current.datum.equals(scrap) && previous == current)
head = current.link;
if (head == null) tail = null;
nodeCount--;
return true;
//node to be deleted is after the first node and before the last
else if (current.datum.equals(scrap) && (current.link != null))
previous.link = current.link;
nodeCount--;
return true;
//node to be deleted is at the ned of list
else if (current.datum.equals(scrap) && (current.link == null))
tail = previous;
previous.link = null;
nodeCount--;
return true;
previous = current;
return false;
//method to display the contents of a linked list
public void displayList()
Node temporary = head;
if (head == null)
IO.screen.println("linked list is empty");
return;
while (temporary != null)
IO.screen.println(temporary.datum);
temporary = temporary.link;
//method to return true if the linked list is empty
public boolean isEmpty()
return (nodeCount == 0);
//method to return the number of nodes in the linked list
public int nodes()
return nodeCount;
//method to display a menu to insert data into the linked list
static private char menu()
char response = '\u0000';
IO.screen.println("Do you want to ");
IO.screen.print("nsert, [D]elete, [L]ist, [E]xit? ");
IO.screen.flush();
boolean done=false;
do
try
String data = IO.keyboard.readLine();
response = Character.toUpperCase(data.charAt(0));
done = true;
catch (Exception e)
IO.screen.println("Please input a single character I, D, L or E");
} while (! done);
return response;
static public void main(String[] args) throws IOException
LinkedList list = new LinkedList();
String datum;
char choice;
//get information from menu
choice = menu();
for (;;)
//Menu
switch (choice)
case 'I' :
IO.screen.println("type quit to finish input");
IO.screen.print("Enter a word ");
IO.screen.flush();
datum = IO.keyboard.readLine();
while (! datum.equals("quit"))
THE ERROR HAPPENS HERE ON THIS LINE list.insert(datum.name);
IO.screen.print("Enter another word");
IO.screen.flush();
datum = IO.keyboard.readLine();
break;
case 'D' :
//if list is empty deletion not possible
if (list.isEmpty())
IO.screen.println("linked list is empty");
break;
IO.screen.println("type quit to finish input");
IO.screen.print("Delete? ");
IO.screen.flush();
datum = IO.keyboard.readLine();
while (! datum.equals("quit"))
if (list.delete(datum))
IO.screen.println(datum+" was scrapped!");
//if list is empty deletion is not possible
if (list.isEmpty())
IO.screen.println("linked list is empty");
break;
IO.screen.print("Delete? ");
IO.screen.flush();
datum = IO.keyboard.readLine();
break;
case 'L' :
list.displayList();
IO.screen.println("number of nodes " + list.nodes());
break;
case 'E' : System.exit(0);
//get information from menu
choice = menu(); -
Implementation of Linked List class
I am trying to implement the Linked List class for one week, but I couldn't figure it out. If you know, please let me know.
Here is an example of a linked list. Hope that will help.
// define a node of a linked list
public class Node
public int data; // point to data
public Node next; // pointer to next node or point to null if end of list
// listTest1
public class ListTest1
public static void main(String[] args)
Node list;
list = new Node();
list.data = 3;
list.next = new Node();
list.next.data = 7;
list.next.next = new Node();
list.next.next.data = 12;
list.next.next.next = null;
Node current = list;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
System.out.println();
// other listnode
public class ListNode
public int data;
public ListNode next;
public ListNode()
// post: constructs a node with data 0 and null link
this(0, null);
public ListNode(int value)
// post: constructs a node with given data and null link
this(value, null);
public ListNode(int value, ListNode link)
// post: constructs a node with given data and given link
data = value;
next = link;
Contents of ListTest2.java
public class ListTest2
public static void main(String[] args)
ListNode list = new ListNode(3, new ListNode(7, new ListNode(12)));
ListNode current = list;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
System.out.println(); -
Is my code a Linked Lists or not?
Hello everyone,
[I hope I am in the right forum]
I am trying to learn how to implement Linked Lists with Java. I have written a small code and I would appreceate it a lot if any one would be kind enough to check if this code is really a linked list.
I tried to make a list with 3 nodes, with no helping methods for adding and removing nodes. Just a simple example. This is my code:
public class myList{
public static final long serialVersionUID = 24362462L;
//node pointer important to define private, so not share same value
private myList pointer;
//node data
private String nodeData;
public static void main(String args[]){
//Give memory to nodes
myList Node1 = new myList();
myList Node2 = new myList();
myList Node3 = new myList();
//Make Node1
Node1.pointer = Node2;//give value to pointer
Node1.nodeData = "Hi i am data contained in Node 1.";
//Make Node2
Node2.pointer = Node3;
Node2.nodeData = "Hi i am data contained in Node 2.";
//Make Node3
Node3.pointer = null;
Node3.nodeData = "Hi i am data contained in Node 3.";
//Display Data
System.out.println(Node1.nodeData);
System.out.println(Node2.nodeData);
System.out.println(Node3.nodeData);
//Display pointers
System.out.println("Hi this is Node2 ==============>:"+Node2);
System.out.println("This is the value of pointer of Node1:"+Node1.pointer);
System.out.println("Hi this is Node3===============>:"+Node3);
System.out.println("This is the value of pointer of Node2:"+Node2.pointer);
}//main
}//class
/***** OUTPUT ***** OUTPUT ***** OUTPUT ***** OUTPUT *****
Hi i am data contained in Node 1.
Hi i am data contained in Node 2.
Hi i am data contained in Node 3.
Hi this is Node2 ========================>:myList@16f0472
This is the value of pointer of Node 1 ==>:myList@16f0472
Hi this is Node3 ========================>:myList@18d107f
This is the value of pointer of Node 2 ==>:myList@18d107f
Press any key to continue...
Thank you very much,
JMelsiHappy to advise. Here we go. :)
Firstly, you'll want to post your code in code tags. They make your code more legible, thus making it easier and therefore more likely that someone responds. ;)
Second, it would be more appropriate for class names (such as "myList") to start with an upper-case letter (such as "MyList"). Additionally, the class in question does not represent a whole list but instead a node, so you might want to call it "MyListNode" or something similar.
Strictly speaking, your code is definitely that of a linked list of nodes. For example, one could print all of the contents in your list with code like this:
myList node = ...; // assign to the first node
while (node!=null) // as long as there is a node
System.out.println(node.nodeData); // print the data in this node
node = node.pointer; // move on to the next node
}Note that, in the above code, I didn't have to know how many nodes were in your list or have any references to them beforehand. :) That's the power in the data structure you're creating.
Enjoy! -
After Delete in Linked list...unable to display the linked list
Hi...i know that there is an implementation of the class Linked Link but i am required to show how the linked list works in this case for my project...please help...
Yes..I tried to delete some objects in a linked list but after that i am not able to display the objects that were already in the linked list properly and instead it throws an NullPointerException.
Below shows the relevant coding for deleting and listing the linked list...
public Node remove(Comparator comparer) throws Exception {
boolean found = false;
Node prevnode = head; //the node before the nextnode
Node deletedNode = null; //node deleted...
//get next node and apply removal criteria
for(Node nextnode = head.getNextNode(); nextnode != null; nextnode = nextnode.getNextNode()) {
if(comparer.equals(nextnode)) {
found = true;
//remove the next node from the list and return it
prevnode.setNextNode(nextnode.getNextNode());
nextnode.setNextNode(null);
deletedNode = nextnode;
count = count - 1;
break;
if (found) return deletedNode;
else throw new Exception ("Not found !!!");
public Object[] list() {
//code to gather information into object array
Node node;
Object[] nodes = new Object[count];
node = head.getNextNode();
for (int i=0; i<count; i++) {
nodes[i] = node.getInformation(); // this is the line that cause runtime error after deleting...but before deleting, it works without problem.
node = node.getNextNode();
return nodes;
}Please help me in figuring out what went wrong with that line...so far i really can't see any problem with it but it still throws a NullPointerException
ThanksOK -- I've had a cup and my systems are coming back on line...
The problem looks to be the way that you are handling the pointer to the previous node in your deletion code. Essentially, that is not getting incremented along with the nextNode -- it is always pointing to head. So when you find the node to delete then the line
prevnode.setNextNode(nextnode.getNextNode());will set the nextNode for head to be null in certain situations (like if you are removing the tail, for instance).
Then when you try to print out the list, the first call you make is
node = head.getNextNode();Which has been set to null, so you get an NPE when you try to access the information.
Nothing like my favorite alkaloid to help things along on a Monday morning...
- N -
Problem with Queue and linked list
Hi... i've got an assignment it start like this.
You are required to write a complete console program in java includin main() to demonstrate the following:
Data Structure: Queue, Priority Queue
Object Involved: Linked-List, PrintJob
Operations Involved:
1. insert
2. remove
3. reset
4. search
Dats all... I've been given this much information... Can any1 try to help me please... How to make a start??? And wat does the print job means???
Can any1 tell me wat am supposed to do...Hi,
Why don't you start your demo like this?
import java.io.IOException;
public class Demo {
public Demo() {
public void startDemo() throws IOException {
do {
System.out.println("String Console Demo ");
System.out.println("\t" + "1. Queue Demo");
System.out.println("\t" + "2. PriorityQueue Demo");
System.out.println("\t" + "3. LinkedList Demo");
System.out.println("\t" + "4. PrintJob Demo");
System.out.println("Please choose one option");
choice = (char) System.in.read();
showDemo(choice);
} while (choice < '1' || choice > '4');
public void showDemo(char ch) {
switch (ch) {
case '1':
System.out.println("You have chosen Queue Demo ");
showOperations();
break;
case '2':
System.out.println("You have chosen Priority Queue Demo ");
showOperations();
break;
case '3':
System.out.println("You have chosen LinkedList Demo ");
showOperations();
break;
case '4':
System.out.println("You have chosen Print Job Demo ");
showOperations();
break;
private void showOperations() {
System.out.println("Please choose any operations ");
System.out.println("\t" + "1. Insert ");
System.out.println("\t" + "2. Remove ");
System.out.println("\t" + "3. Reset ");
System.out.println("\t" + "4. search ");
public static void main(String[] args) throws IOException {
Demo demo = new Demo();
demo.startDemo();
private char choice;
Write a separate classes for the data structures show the initial elements and call the methods based on the operations then show the result.
Thanks -
Can I import my old link lists into 365 site?
Hi I would like to import all my hard work from my old 2010 sharepoint site into the new 365 site.
I exported my links to excel but I cannot see an import option on a link list in 365.
Surely there must be an easy way to do this that I am missing?
thanksBelow are the steps to save List as Template:
>> Go to the List - List Settings - Click on Save List as Template - Provide Template Name and make sure you check the "With Content" box available on the page.
Once the List is successfully saved as template, you will find the template under List Templates gallery. Download that template it should have ".stp" extension. Get that file and upload the file to List Templates gallery of your SharePoint Online Office
365 site. Then create a new app and there you should find the Template and create a list using that template.
If you have any questions then let me know.
Please ensure that you mark a question as Answered once you receive a satisfactory response.
Maybe you are looking for
-
I cant figure out how to install addons for Safari for Windows. Is it possible. I downloaded the file from other websites, but i dont know what to do with them or where to put them and such. Can anyone help me, if it isnt possible, is thee any progra
-
Greetings All, I created two time series measures in a fact table using AGO and TODATE - e.g., last month sale and year to date sales In Answer when I select one of these two fields the data returned are correct. However, when I select both fields in
-
Best way to handle optional elements in XSLT
Hi All, I'v wondering if there are any better ways to handle optional fields in XSLT. For example if my Person Type has 5 fields and 3 of them are optional: <xs:complexType name="PersonType"> <xs:element name="PersonID" min="1"/> <xs:element name="PI
-
Deactivate the drill path selection
Hi everybody! When more than one hierarchy starts with the same dimension object path but diverges at a lower level of the hierarchy Web Intelligence prompts and asks for the applied drill path! In the universe documentation I found the sentence: The
-
Is there any 3G or LTE built in on my MacBook Pro