I am writing a class to sort objects by name field. I assume work with different types, therefore I use generic

public static <T> List<T> sortStringList(List<T> list, Class type){ List <Integer> numList = new ArrayList(); for (T item : list) { if (item.getClass() == type && type == SubCategory.class) { System.out.println("It subcategory"); } if (item.getClass() == type && type == Category.class) { } } return list; } 

In the condition I determined with which type I was working, but how now in the list should I change T to the type I need? That is, so that I have for example a list with elements of type Category. I need this in order to access the fields of the Category object.

  • one
    Explicitly cast the list item to the desired type? ((Category) list.get(0)).categoryMember ? - post_zeew
  • Yes, right, I just did not know about type conversion. Thank! - Yegor Podolyak
  • one
    If the decision is correct, please click on the check mark next to the answer. - post_zeew
  • 2
    But in general, you should remember that such frills, talk about the problem in the design of the class. - Nofate

1 answer 1

To access a field / method, you must first explicitly convert the list item to your type:

 ((Category) list.get(0)).categoryMember 

But in general, in my opinion, the original problem of sorting is solved in another way.


In addition to this answer, I will describe the method that I had in mind above.

This method consists in implementing the interface Comparable objects, sets of which will be sorted.

Suppose there is a certain object - an animal that has a parameter - weight. It is necessary to sort the list of animals by increasing their weight. To perform this task, create an Animal class that implements the Comparable interface:

 public class Animal implements Comparable { private float mWeight; public Animal(float weight) { mWeight = weight; } public float getWeight() { return mWeight; } public void setWeight(float weight) { mWeight = weight; } @Override public int compareTo(Object o) { float diff = this.mWeight - ((Animal) o).mWeight; if (diff > 0) return 1; else if (diff < 0) return -1; else return 0; } } 

Now we can sort a collection of such animals using Collections.sort(...) :

 List<Animal> animals = new ArrayList<>(); animals.add(new Animal(10.3f)); animals.add(new Animal(10.1f)); animals.add(new Animal(10.2f)); Collections.sort(animals); 
  • But in my task it is necessary to sort the rows as numbers, that is, now the sorting works like this: A.1 First category A.10 Tenth category A.11 Next category A.2 Second category. You need to take the numbers from the lines, sort them and swap objects in the list of categories. - Yegor Podolyak
  • @EgorPodolyak; This problem is solved in a similar way. - post_zeew