How to create multiple copies of a given object
package com.java2novice.collections;
import java.util.Collections;
import java.util.List;
public class MyObjectNCopies
{
public static void main(String a[])
{
String
temp = "Java2novice";
List
tempCopies = Collections.nCopies(5, temp);
System.out.println(tempCopies);
Empy
emp = new Empy(10, "Raghu", 25000);
List
empCopies = Collections.nCopies(5, emp);
for(Empy
e:empCopies)
{
System.out.println(e);
}
}
}
class Empy
{
private int id;
private String name;
private Integer
salary;
public Empy(int id, String name,
Integer sal)
{
this.id
= id;
this.name
= name;
this.salary
= sal;
}
public int getId()
{
return
id;
}
public void setId(int id)
{
this.id
= id;
}
public String getName()
{
return
name;
}
public void setName(String
name)
{
this.name
= name;
}
public Integer
getSalary()
{
return
salary;
}
public void
setSalary(Integer salary)
{
this.salary
= salary;
}
public String
toString()
{
return
id+" "+name+" "+salary;
}
}
How to replace all occurances of a given object in the list
package com.java2novice.collections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MyListReplaceAll
{
public static void main(String a[])
{
List
list = new ArrayList();
list.add("java");
list.add("c");
list.add("c++");
list.add("unix");
list.add("perl");
list.add("php");
list.add("javascript");
list.add("ruby");
list.add(".net");
list.add("perl");
list.add("c++");
System.out.println(list);
Collections.replaceAll(list,
"perl", "dum_dum");
System.out.println(list);
}
}
How to rotate elements in the list by specified distance
package com.java2novice.collections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MyListRotate
{
public static void main(String a[])
{
List
list = new ArrayList();
list.add("java");
list.add("c");
list.add("c++");
list.add("unix");
list.add("perl");
list.add("php");
list.add("javascript");
list.add("ruby");
list.add(".net");
System.out.println(list);
Collections.rotate(list,
3);
System.out.println("List
after rotation:");
System.out.println(list);
}
}
No comments:
Post a Comment