I'm very new to Java and struggling to understand generics, the ways they can be used, and the syntax for doing so.
I've the following class
class MyCustomArray<T>{
private T[] myArray;
// Default Constructor
public ArraySet(){
this.myArray= (T[]) new Object[10];
}
// Method to get array length
public int getSize(){
return this.myArray.length;
}
... some random code
// Method to iterate
public void iterateSomehow(MyCustomArray<? extends T> collection){
// doesn't work
for(T obj: collection){...}
// doesn't work
for(int i=0; i< collection.size(); i++){
T nextObj= collection[i];
}
}
}
This is for a class assignment, which disallows the use of standard classes like ArrayList
. I feel like I'm missing something fundamental here, but don't know what.
Is my approach wrong? Is it just syntactical?
Some more context:
My immediate goal is to check each value in the given collection
object as such (psuedo-code, clearly):
for( int i=0; i < collection.length; i++ ):
value = collection[i];
if (value == badValue):
// whatever
Only arrays can be indexed with the []
syntax, and only arrays or classes implementing Iterable
can be used in the right hand side of an enhanced for loop ( for (T xxx: yyy)
). Your class is not an array and does not implement Iterable
, so neither of your attempts worked.
Your class contains an array though - myArray
. You can just iterate through that. Both of these are fine:
for(T obj: collection.myArray){...}
// or
for(int i=0; i< collection.getSize(); i++){
T nextObj= collection.myArray[i];
}
I also feel like your method should not have the parameter and should iterate over this
instead (if this is actually a requirement of the homework, then it can't be helped):
for(T obj: myArray){...}
for(int i=0; i< getSize(); i++){
T nextObj= myArray[i];
}
You can't iterate though collection directly(because it's just object) you should access to myArray. You also can implement Iterable interface, it's allows you something like this
for(T obj: collection){...}
https://www.geeksforgeeks.org/java-implementing-iterator-and-iterable-interface/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.