Good day All,
Normally, I will print all the content in List by look the list.size() and assign it to an object and print the object value. The following is my example code:
List ccUserList = new ArrayList(); // Here I declare a List
Collection ccGroupCol = new ArrayList(); // Here I declare a collection
CCuserBO bo = null;
ccUserList = getSummaryList();
for(int i = 0, i < ccUserList.size() , i++){
bo = ( CCUserBO ) ccUserList.get(i);
System.out.println(bo.userName);
}
I would like to ask about the way to print content in Collection.
Since Collection no have .get() function.
The following in the code that I try in Collection:
CCuserBO newBo = null;
ccGroupCol = getSummaryList();
Iterator iterator = ccGroupCol.iterator();
while ( iterator.hasNext()){
newBo = iterator.next(); //error here, Type mismatch: cannot convert from Object to //Object[]
System.out.println("....");
}
If you simply want to print all elements of a Collection just sysout Collection directly it will provide you the following form in output: [element1, element2, ....] because toString() method is overrided and implemented to provide such output for all Collection classses.
By using Iterator you can get the element one by one:
Iterator iterator = ccGroupCol.iterator();
while ( iterator.hasNext()){
newBo = (**type cast here to particular newBo object type**)iterator.next();
System.out.println(newBo);//here whatever you implemented in toString() method
// in newBo type class(if you did so), you will get that type of output, if you do not override
//toString() to provide your implementation,you will get default implementation in
//which it will show <the object class>#<its hash code>
}
Note: the return type of iterator.next() is Object type, so you must type cast it to avoid incompatible type exception. Or use Generics.
I found the solution. Here is the example code:
CCGroupBO newBo;
for(int i = 0 ; i < ccGroupCol.size() ; i++){
newBo = ( CCGroupBO ) ccGroupCol.toArray()[i];
System.out.println(newBo.getGroupName());
}
Thanks for all your help.
You can use the for loop to iterate the collection.
Collection collection= new ArrayList();
for (Object obj : collection) {
//Here you can type cast the obj then you can print.
}
As statet in comment, a faster solution for your own answer:
Collection<CCGroupBO> ccGroupCol = new ArrayList<CCGroupBO>()
…
CCGroupBO[] boArray = ccGroupCol.toArray();
for(CCGroupBO newBo : boArray){
System.out.println(newBo.getGroupName());
}
or even more direct:
Collection<CCGroupBO> ccGroupCol = new ArrayList<CCGroupBO>()
…
for(CCGroupBO newBo : ccGroupCol){
System.out.println(newBo.getGroupName());
}
depending on other circumstances there is even a nicer method:
class CCGroupBO {
…
public String toString() {
return getGroupName();
}
}
…
Collection<CCGroupBO> ccGroupCol = new ArrayList<CCGroupBO>()
…
System.out.println(ccGroupCol);
Related
I have below list defined,
List<BigDecimal> empList = new ArrayList<BigDecimal>();
And as per below code if condition throws error The type of the expression must be an array type but it resolved to List
for(int i1=0;i1<12;i1++) {
if(empList[i1]==null){
empList[i1]= new BigDecimal("0.00");
}
}
The same code works well in Groovy but does not work in Java.
Looks like a syntax error . In java list are accessed as
empList.get(i1)
and
empList.set(i1,new BigDecimal("0.00"))
or you are free to use array instead of List but in this case you will have to define the array length which stays fixed.
BigDecimal[] empList = new BigDecimal[10];
It has to be :
for (int i1 = 0; i1 < 12; i1++) {
if (empList.get(i1) == null) {
empList.set(i1, new BigDecimal("0.00"));
}
}
A list collection needs has its own methods. Use those.
I have a servlet which gets variables from a form and stores them in a vector.
I want to pass the whole vector to a method in another java class.
How am I supposed to do for that?
This is what I have tried:
In servlet-
private DbUpdate dbup = new DbUpdate();
int j=0;
Vector<String> v = new Vector<String>();
v.addElement("name");
v.addElement("profession");
Enumeration vEnum = v.elements();
j = dbup.insertValues(vEnum);
DbUpdate.java class
public int insertValues(Enumeration vc) {
for (int j=1; j<14; j++) {
statement.setString(j, vc.get(j));
}
i = statement.executeUpdate();
}
It says I cannot have vc.get() method here.
Any help would be highly appreciated.
Thanks in advance.
That's really strange why you are still using such kind of obsolete classes even you are using JDK 1.5+.
Use List instead.
List<String> params = Arrays.asList("name", "profession");
// if you prefer you can also create an ArrayList<String>() and add it one by one
dbUp.insertValues(params);
and in you DbUpdate.java, do something like
public int insertValues(Collection<String> params){
int i = 0;
for (String param : params){
statement.setString(++i, param);
}
return statement.executeUpdate();
}
Edit:
If in any case you really really want to use Enumeration, you need to understand Enumeration works similar to an Iterator which provide you an interface to iterate through a collection of object. Hence it should look something like:
public int insertValues(Enumeration<String> params){ // or use Enumeration<?>, but you need
// further casting below
int j = 0;
while (params.hasMoreElements()) {
String param = params.nextElement();
statement.setString(++j, param);
}
return statement.executeUpdate();
}
If you iterate all elements of enum, you can use below code
for(Enumeration e : vc.values())
Iterate over Enumeration using following two methods,
hasMoreElements()
Tests if this enumeration contains more elements.
nextElement()
Returns the next element of this enumeration if this enumeration
object has at least one more element to provide.
You need to modify your insertValues() method,
public int insertValues(Enumeration vc){
while(vc.hasMoreElements()){
if(j<14){
statement.setString(j, vc.get(j));
j++;
}
}
i = statement.executeUpdate();
return 0; // return what you want to return
}
I wrote a function for my cache to retrieve a specific object. This way I don't need to cast it .
#SuppressWarnings("unchecked")
public static <T> T inCache(Class<T> obj, String token) {
Object cacheObj = Cache.get(token);
if (cacheObj != null) {
if (obj.isAssignableFrom(cacheObj.getClass())) {
return (T) cacheObj;
}
}
return null;
}
I am using it like this
String s = inCache(String.class, title);
But now I have a list of Strings in my cache and I can't use it like this
List<String> ipList = Util.inCache(List<String>.class, title);
The problem is the List<String>.class . I am very new to java, how do I have to write it?
There is a concept in java called type erasure. Due to legacy reasons, something like List is just a list. It doesn't remember that it is a list of string at run time. You should just write List.class.
You can then specify the type of object in the List when iterating through it.
You can't get class of List<String>, in your case the only way is:
List<String> ipList = (List<String>)Util.inCache(List.class, title);
You can try :
List<String> ipList = Util.inCache(List.class, title);
Try this-
List<String> inList = (List<String>)Test.inCache(List.class, title);
And you can do also -
List<String> inList = Test.inCache((Class<? extends List<String>>)List.class, token);
Just to clarify Joe's answer ( I don't have enough reputation to comment), at runtime there is no difference between a List <String> and List<Integer> or any other type of List, generics aren't kept at runtime.
Meaning, List<String>.class is completely identical to List<Integer>.class and is actually List.class. This is a weakness of the Java type system. I'm not familiar with a simple way to implement what you wish for.
A code proof for the heck of it :
// It is true that
List<String> stringList = new ArrayList<String>();
List<Integer> integerList = new ArrayList<Integer>();
System.out.println( stringList.getClass() == integerList.getClass() );
// And that ...
List objectList = new ArrayList();
System.out.println( stringList.getClass() == objectList.getClass() );
//However, the following is false because a different implementation is used ( I wanted a false case)
List objectLinkedList = new LinkedList();
System.out.println( objectLinkedList.getClass() == objectList.getClass() );
I have a piece of code like this:
HashSet<Object> Set = new HashSet<Object>();
//add elements to set 'Set'
Object o = null;
for (Iterator<Object> itr=Set.iterator();itr.hasNext();) {
o = itr.next();
//doing some processing on o
}
I assumed that Object o will point to the Object pointed to by itr. But it is not working as expected. The attributes pointed to by itr.next() is not being copied to o.
Can anybody suggest where I am going wrong? And also, is there some useful post on object assignment like
o1 = o2
and what happens at memory level in Java?
Below is my actual code:
What I am doing: I have created a set TSet of elements of type Types.AdjList and now I want to process each successive pair of elements of type Types.AdjList and have assigned iterator value during each iteration to two Types.AdjList variables T1 and T2. But T1 and T2 attributes are not matching what the iterator is having.
P.S. Types.AdjList is a HashMap
for (int i=0; i<numT; i++) {
size = generator.nextInt(10)+1;
T[i] = new Types().new AdjList(size);
}
HashSet<Types.AdjList> TSet = new HashSet<Types.AdjList>();
for (int i=0; i<T.length; i++) {
TSet.add(T[i]);
}
Types.AdjList T1 = null, T2 = null;
for (Iterator<Types.AdjList> itr = TSet.iterator(); itr.hasNext();) {
T1 = itr.next();
if (T2 != null) {
size1 = T1.adj.size();
//size1 is returning 0, though T1.adj has some elements
size2 = T2.adj.size();
//do some processing on T1, T2 based on size1 and size2
}
T2 = T1;
}
Any help will be appreciated.
Thanks,
Somnath
There is nothing wrong with your code, but it could use some cleaning up.
If you apply these "best practice" coding standards:
Always declare the abstract type (ie Set not HashSet)
Use leading-lowercase names for variables (set not Set)
Use "foreach" syntax where possible (dispense with using iterators directly)
Declare variables so they have the smallest scope possible (o lived past its use)
you get your code refactored to:
for (Object o : new HashSet<Object>(someSet)) {
// doing some processing on o
}
or even
for (Object o : someSet) { // Not sure why you wanted to make a new Set
// doing some processing on o
}
Where does t2 get set from? It looks like it's always null to me, and therefor the if statement never gets executed. Put a break point there and see what happens.
We don't use iterators in Java anymore:
We use 'in'
ArrayList<String> stringList = new ArrayList<String>();
// initialize it with code (not shown)
for (String s: stringList) {
System.out.println("the current element is:" + s);
}
You are not iterating correctly.
you need to do
HashSet set = ...
Iterator _i = set.iterator();
while(_i.hasNext()) {
Object o = _i.next();
}
start there.
Also, as to your question
o1 = o2
Nothing happens to memory. In java, everything is either a primitive or a class. All classes reside in the heap, so o1 = o2 just copies the pointer to o2 over to the variable o1. If o2 is a primitive, it copies the value (rather than a pointer) into o1
Hello I am having the same problems taking data from a collection with an iterator:
I have a class called DatabaseTableFieldUIData which has a method getFieldName.
In another class I have a collection of DatabaseTableFieldUIDatas like this:
Collection columnData
Now I want to go through that collection with an iterator to get all the field names with getFieldName method. So I tried something like this:
Iterator<DatabaseTableFieldUIData> it = columnData.iterator();
for (int i = 0; i < columnData.size(); i++)
String fieldName = it.getFieldName();
but it doesn't allow me to call getFieldName method from the iterator, so I tried casting the iterator to DatabaseTableFieldUIData:
Iterator<DatabaseTableFieldUIData> it = columnData.iterator();
DatabaseTableFieldUIData aux;
for (int i = 0; i < columnData.size(); i++)
aux = (DatabaseTableFieldUIData) it;
And I get the error "Cannot cast from Iterator to DatabaseTableFieldUIData", don't know what to do right now :(
Thanks for the help.
You need to call it.next() to get the object "pointed to" by the iterator.
See http://download.oracle.com/javase/1,5.0/docs/guide/language/foreach.html for guidance on using iterators.
An Iterator is not a DatabaseTableFieldUIData This literally million of examples of how to use an Iterator correctly.
If you use a for-each loop, you don't need an Iterator at all.
for(DatabaseTableFieldUIData aux: columnsData) {
Try this:
Iterator<DatabaseTableFieldUIData> it = columnData.iterator();
while(it.hasNext()){
DatabaseTableFieldUIData data = it.next();
String fieldName = data.getFieldName();
}
Or better:
for(DatabaseTableFieldUIData data : columnData){
String fieldName = data.getFieldName();
}