Make a list of different objects Java -



Make a list of different objects Java -

i'm trying create list of different objects.

i know can create list of object, example:

arraylist<matrices> list = new arraylist<matrices>(); list.add( new matrices(1,1,10) ); list.add( new matrices(1,2,20) );

but want create list can this:

list.add (new object1(a,b,c)); list.add (new object2(e,f));

obviously object1 , object2 different.

please, give me hand here.

vytenis' reply technically correct, not should doing on regular basis. more extensible solution create interface , have both objects implement, letting list hold both objects without losing safety , advantages come statically typed lists. while java not multiple inheritance classes, implementing multiple interfaces no problem.

for example, take class declarations:

class object1{ ... } ... class object2{ ... }

and add together next interface declaration @ top level somewhere -

public interface sharedtype{ ... }

for each object want store, have implement interface this:

public class object1 implements sharedtype{ ... }

when declare list, declare this:

list<sharedtype> mylist = new arraylist<sharedtype>();

or whatever type of list you're trying create, doesn't have arraylist

this won't work built in types or classes who's declaration can't change

using interfaces types mutual practice in java, see http://docs.oracle.com/javase/tutorial/java/iandi/interfaceastype.html , example

edit

if need store different built in types (like strings , integers), suggested in comments, consider making wrapper object around them. cumbersome, you're not able alter declaration of built-in classes, , using generic type object should lastly resort, subverts reason of requiring type specification in first place.

for example,

interface wrapper{} class stringwrapper extends wrapper{ string s; public stringwrapper(string s){ this.s = s; } } class intwrapper extends wrapper{ string i; public stringwrapper(integer i){ this.i = i; } }

someone looking @ code (including you, later on), know trying utilize in list. still advantages of java's static typing

java

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -