Reputation: 516
I have two types of for loops, fileList
in this case is just a custom class that extends AbstractList<Object>
1) For loop iterating by index:
public String getExtensionByDescription(String description)
{
for (int i = 0; i < fileList.size(); i++)
if (description.contains(fileList.get(i).getDescription()))
return fileList.get(i).getExtension();
}
2) For loop iterating by item in list:
public String getExtensionByDescription(String description)
{
for (FileType obj : fileList)
if (description.contains(obj.getDescription()))
return obj.getExtension();
}
Are method 1) and 2) logically the same or no? Because 1) returns the value i expect but method 2) returns the wrong value. Thanks for the help!
The implementation of list with various other get methods.
public class FileList extends AbstractList<Object>
{
private ArrayList<FileType> fileList;
public FileList()
{
fileList = new ArrayList<FileType>();
}
public void add(String search, String type, String extension, String description, String htmlicon)
{
FileType data = new FileType(fileList.size(), search, type, extension, description, htmlicon);
if (!fileList.contains(data))
{
fileList.add(data);
}
}
@Override
public Object get(int index)
{
return fileList.toArray()[index];
}
and the other class is
public FileType(int index, String search, String type, String extension, String description, String icon)
with function:
public String getDescription()
{
return description;
}
Upvotes: 0
Views: 149
Reputation: 106389
You may have a few things conflated here.
ArrayList
.get
, which was guaranteed to give you back the result you wanted when using it, but didn't consider the iterator()
.Ultimately, there was no reason for you to extend AbstractList
at all. Just use the backing list instead.
To do that, create a getter for it:
public ArrayList<FileType> getFileList() {
return fileList;
}
...and then use it in your iteration:
for(FileType type : fileList.getFileList()) {
// logic here
}
It would then behave no differently to your get
.
Upvotes: 0
Reputation: 18825
If it was correct implementation of List
, then they would be logically the same (although they could differ in terms of performance).
If they give different results then either get(int)
method or iterator()
method doesn't behave as expected, i.e. doesn't return i
-th element or doesn't traverse through all elements respectively.
EDIT: After update of the question the issue is clear - you override get(int)
method (although it returns Object but in the code it's accessed as FileType - looks suspicious). But there is no override of iterator()
method. The Iterator
which is returned by iterator()
is actually used in the second for loop transparently by the compiler. Unless you override the code could never work.
Upvotes: 5