Java LinkedList store User-Defined Classes

Introduction

We can store our own classes in Collections

Full source

// A simple mailing list example.  
import java.util.LinkedList;  
  
class Address {  
  private String name;  
  private String street;  
  private String city;  
  private String state;  
  private String code;  
  
  Address(String n, String s, String c,   
          String st, String cd) {  
    name = n;  //from w  w w. jav a 2s  .co m
    street = s;  
    city = c;  
    state = st;  
    code = cd;  
  }  
  
  public String toString() {  
    return name + "\n" + street + "\n" +  
           city + " " + state + " " + code;  
  }  
}  
  
class MailList {  
  public static void main(String args[]) {  
    LinkedList<Address> ml = new LinkedList<Address>();  
      
    // Add elements to the linked list. 
    ml.add(new Address("Java", "1 MIN Ave",  "Urbana", "IL", "12345"));  
    ml.add(new Address("CSS", "1 Main Lane",  "Mahome", "IL", "12345"));  
    ml.add(new Address("Javascript", "8 OK St","Champaign", "IL", "544321"));  
 
    // Display the mailing list. 
    for(Address element : ml) 
      System.out.println(element + "\n");  
 
    System.out.println();  
  }  
}



PreviousNext

Related