Create multiple objects in Java.


Enjoyed this post? Tell others about it! DeliciousDelicious | twitterTwitter | redditReddit | diggDigg

Let's create some objects. We have three classes.
	public class Human 
	{
		private String name;
		
		public Human(){
			name="";
		}
		
		public Human(String name)
		{
			
		}
		
		public String getName()
		{
			return this.name;
		}
		
		public void setName(String name)
		{
			this.name=name;
		}
	}
	public class Man extends Human
	{
		
	}
	public class Woman extends Human
	{
		
	}
	List women = new ArrayList();
	List men = new ArrayList();
	
	
	for(int i = 0; i < 100; i++)
	{
		womans.add(new Woman());
		men.add(new Man());
	}
Now if you do much thing like this you write much for-loops. I found a solution for this kind of problem without writing a new for loop. Lets add a Method in the Human class.
	public static List getInstances(Class clazz, int counter)
	{
		List humans = new ArrayList();
		
		for(int i=0;i< counter; i++)
		{
			
			humans.add(clazz.newInstance());
		
		}
		
		return humans;
	}
Now you can use this for creating humans.
	List men = Human.getInstances(Men.class,10);
	List men = Human.getInstances(Women.class,10)
If you have a specific constructor you can use this
	public static List getInstances(Class clazz,String name, int counter)
	{
		List humans = new ArrayList();
		
		for(int i=0;i< counter; i++)
		{
			
			humans.add(clazz.getDeclaredConstructor(String.class)
				.newInstance(name));
		
		}
		return humans;
	}

Enjoyed this post? Tell others about it! DeliciousDelicious | twitterTwitter | redditReddit | diggDigg

blog comments powered by Disqus