Java Collections

Collections are a set of data performing administration of all abstract datatypes. ( e.g searching,sorting,inserting,delete).Collections are very helpful by providing useful data structures and reduce programming effort. The disadvantages are casting to correct type of object and compile-time type checking is not possible.

Simple List example:

String[] text ={"Apple","Potato","Tomato","Onion"};
List<String> lts = new ArrayList<String>();
lts = Arrays.asList(text);// make it serializable and implement random access

Now we want to represent our data as output. I want you to introduce a solution with an iterator.

Iterator<String> iter = lts.iterator();
while(iter.hasNext()) {
System.out.println(iter.next());
}

Illustration of Iterator:

Every iter.next() represents our object.This is a typical Linked List.

Output:

Apple
Potato
Tomato
Onion

Now we add class objects to our list.First we create our Model Book.

 

public class Book {
	private String name;
	private String author;
	private String isbn;
	
	
Book(String name,String author,String isbn){
	this.setName(name);
	this.setAuthor(author);
	this.setIsbn(isbn);
}


public String getName() {
	return name;
}


public void setName(String name) {
	this.name = name;
}


public String getAuthor() {
	return author;
}


public void setAuthor(String author) {
	this.author = author;
}

Main class

public class Main {

	public static void main(String[] args) {
        
		Book b1 = new Book("Harry Potter","Rowling","978-3551555557");
		List<Book> books = new ArrayList<Book>();
		books.add(b1);
		System.out.println(books.get(0).getName()+","+books.get(0).getAuthor()+","+books.get(0).getIsbn());
	}

}

Result: Harry Potter,Rowling,978-3551555557

Leave a Reply

Your email address will not be published. Required fields are marked *