Use case
You have a Book Class with several attributes, and you have to create a list from existing list and have the new list modified for a single attribute.
public class Book implements Cloneable{
private String bookName;
private String bookAuthor;
private String bookId;
public Book(String bookAuthor,String bookName,String bookId){
this.bookAuthor=bookAuthor;
this.bookName=bookName;
this.bookId=bookId;
}
public Book(){
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getBookAuthor() {
return bookAuthor;
}
public void setBookAuthor(String bookAuthor) {
this.bookAuthor = bookAuthor;
}
public String getBookId() {
return bookId;
}
public void setBookId(String bookId) {
this.bookId = bookId;
}
protected Object clone() throws CloneNotSupportedException {
Book clone=(Book)super.clone();
return clone;
}
}
import java.util.ArrayList;
import java.util.Iterator;
public class TestFunctionality {
/** You have a Book Class with several attributes, and you have to create a list from existing list and have the new list modified for a
* single attribute.
*
*
**/
public static void main(String []arg){
ArrayList <Book>bookArrayList=new ArrayList<Book>();
ArrayList <Book>bookArrayList1=new ArrayList<Book>();
Book b1=new Book("Sachi","AA123","CoreJava");
Book b2=new Book("Sachii","AA1234","CoreJavaa");
Book b3=new Book("Sachiii","AA12345","CoreJavaaaa");
bookArrayList.add(b1);
bookArrayList.add(b2);
bookArrayList.add(b3);
Iterator<Book> bookListIterator = bookArrayList.iterator();
while (bookListIterator.hasNext()){
Book b=new Book();
try {
b=(Book) bookListIterator.next().clone();
System.out.println(b.getBookAuthor());
b.setBookAuthor("SACH");
bookArrayList1.add(b);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
int length=bookArrayList1.size();
System.out.println("Length of the new list is " + length);
Iterator<Book> bookListIterator1 = bookArrayList1.iterator();
while (bookListIterator1.hasNext()){
System.out.println(bookListIterator1.next().getBookAuthor());
}
}
}
No comments:
Post a Comment