Showing posts with label TreeSet. Show all posts
Showing posts with label TreeSet. Show all posts

Use of Collection Framework

Use of Collection Framework Classes and Interfaces

ArrayList, TreeSet, Iterator

import java.util.*;
public class Book implements Comparable{
/**
Unique Book ID
                */
public int book_id;
protected String title;
/**
Book Price including GST
                */
private float price;
/**
Constructor
                */
public Book(int id, String title, float price){
this.book_id = id;
this.title = title;
this.price = price;
}
public int compareTo(Object o1){
return this.book_id-(((Book)o1).book_id);
}
public String toString(){
return this.book_id+"#"+this.title+"#"+this.price+"@";
}

public static String ObjToString(Book c[]){
String str = new String();
for(int i=0;i<c.length;i++){
str = str+c[i];
}
return str;
}

public static Book[] StringToObj(String str){
String[] st = str.split("@");
Book b2[] = new Book[st.length];
for(int i=0; i<st.length;i++){
String st1[] = st[i].split("#");
b2[i] = new Book(Integer.parseInt(st1[0]),st1[1],Float.parseFloat(st1[2]));
}
return b2;
}

public static void main(String args[]){
Book b[] = new Book[3];
b[0] =new Book(1,"Java", 100);
b[1] = new Book(2,"ADA", 200);
b[2] = new Book(3,"SP", 300);
//ArrayList a1 = new ArrayList();
TreeSet a1 = new TreeSet();
a1.add(new Book(2,"ADA", 200));
a1.add(new Book(2,"ADA", 200));
a1.add(new Book(1,"Java", 500));
a1.add(new Book(4,"MI", 800));
// Collections.sort(a1);
Iterator ir = a1.iterator();
while(ir.hasNext())
{
System.out.println((Book)(ir.next()));
}
System.out.print(a1);
/*System.out.print(Book.ObjToString(b));
String str1 = ObjToString(b);
Book c[] = StringToObj(str1);
for(int i=0;i<c.length;i++){
System.out.print(c[i]);
}*/
}
}