sorting custom object array on two fields - android

I'm sorting an array of custom objects (ListData[]) on two fields. I want it to be sorted by theme, and them by name. I thought i made a nice comparator in the custom object class and that i could use Arrays.sort(ld) to make my code working and sorting my array. But apparently im doing something wrong...
my custom object:
public class ListData implements Comparable<ListData>{
public int venueID;
public String name;
public String photoUrl;
public String tip;
public String theme;
#Override
public int compareTo(ListData ld0) {
return this.venueID- ld0.venueID;
}
public static Comparator<ListData> ListDataThemeAndNameComparator = new Comparator<ListData>() {
#Override
public int compare(ListData ld1, ListData ld2) {
String compareTheme1 = ld1.theme.toUpperCase();
String compareTheme2= ld2.theme.toUpperCase();
String compareName1 = ld1.name.toUpperCase();
String compareName2= ld2.name.toUpperCase();
//ascending
int comp = compareTheme1.compareTo(compareTheme2); // comp themes
if(comp==0){ // same theme
comp= compareName1.compareTo(compareName2); // compare names
}
return comp;
}
};
}
And in my main activity i have:
ListData ld[]= new ListData[jsonResponse.size()];
(some code filling my ListData array)
Arrays.sort(ld, ListData.ListDataThemeAndNameComparator); // compare by theme and then by name
Does anyone know what i'm doing wrong?
I edited my code But still it fails, now on a nullpointerexception on the compareTheme1 = ld1.theme.toUpperCase();. But i am sure my array is not empty, i logged it the line before sorting it and its filled with about 500 items.

Your ListData object should implements Comparable not Comparator interface.
EDIT:
To make things clear, you can sort an array by Array.sort(). To make custom sort, you can specify your comparator in Array.sort(), if you don't do that, array will be sorted in natural order which you can define by implementing Comparable interface. So you have two options how to custom sort:
by using custom comparator and specifying it in Array.sort()
by implementing Comparable interface to your items
I would suggest you to go with implementing Comparable. You save memory by not creating new comparator objects and Comparator is useful if you are comparing objects of different types which is not your case.

Related

How to sort list that has custom element (not string or int)?

I'm using the flutter_secure_storage package and I'm trying to sort the items in the list. The list is like: List<_SecItems> hi = []
and defined by:
class _SecItem {
_SecItem(this.key, this.value);
final String key;
final String value;
}
The order of items in the list isn't kept. And using hi.sort() gives the message type '_SecItem' is not a subtype of type 'Comparable<dynamic>'
So how would I sort the strings in the list of _Secitem elements? The elements inside of List<_Secitems> are still strings.
you can sort object like this
hi.sort((a, b) => b.value.compareTo(a.value));
Implement Comparable and write the logic in compareTo().
class _SecItem implements Comaparable<_SecItem> {
_SecItem(this.key, this.value);
final String key;
final String value;
public int compareTo(Student st){
}
}

Is this a good practice? (Class fields)

I need to have a relatively large number of categories defined (about 30 at start, we'll be adding more). Consider this code:
public class Category {
public static final Category DRESS = new Category("Dress");
public static final Category SKIRT = new Category("Skirt");
...
private static final List<Category> CATEGORIES = Arrays.aslist(DRESS, SKIRT, ...);
private String name;
public Category(String name) {
this.name = name;
}
//Some static public method to iterate over categories
...
I need to have the categories declared and also need a way to iterate over them. I discard reflection because I think it's not a very good practice.
Is declaring a large name of static final fields of the same class and also having them inside a list a good practice? As an alternative, I thought about having a Map<Integer, Category> instead the list, and the fields were integers that would identify each category, so you would get the categories by getting them inside the map. Would this be better in terms of time and space performance?
PS: It's for an android project, if it changes something
Consider this code:
public class Category {
public static final Category DRESS = new Category("Dress");
public static final Category SKIRT = new Category("Skirt");
Yeah this is literally what enums do in the background, so
public enum Category {
DRESS("Dress"),
SKIRT("Skirt"),
...;
private String name;
private Category(String name) {
this.name = name;
}
// Category.values() returns the elements as an array
You should use enum instead of creating an object with new Category("Dress"); because creating an object is expensive than using enum. Java enums are implemented more like classes, so you can change your code seamlessly:
public enum Category {
DRESS("Dress"), SKIRT("Skirt");
private final String name;
Category(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Note:
The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself.
Read more about enum at Enum Types
I would say using a List is good enough.
You should consider a Map only if you have to look up a
particular Category very frequently via some key property (like an int your case).
If There are no properties or methods in the Category class consider replace them with just Strings.
If new Categories are created at runtime and you want to persist them consider using a DB or File to save the Categories.
Edit: Answering the question in the comment
That would depend on the Category class. If its only purpose is to enumerate all the categories and the class itself does not have any other instance methods or properties then in terms of space complexity an Integer and your Category class is similar (since in a Map integer will be boxed in the Integer class object)
I would still suggest that you use a class called Category and a list if the purpose is only iterating over them and/or using specific instances of the Category class elsewhere in your application eg. Category.SOME_CATEGORY.
The following example is a good use-case
someMethod(Category category) {
// do something
}
versus
someMethod(int category) {
// before doing anything
// lookup this category by an int key
// in the the Map<Integer, Category>
}
The problem with the latter is that you could pass any int which may or may not be a valid key for a category. Using a class gives some bit for extra compile time check. Though you could always use an int def too. But again I would repeat that it all boils down to whether Category class has any instance methods or properties.
For small list, it is okay to use List or Map.
But for a large list, you may want to store them in a database.
Also ArrayList of String will be slightly efficient than using ArrayList of Category

How to find index in ArrayList<Class> (Android)

I use eclipse android
I need to index or object find in ArrayList
public class myclass
{
int id;
int count;
String value;
}
mainactivity
{
ArrayList<myclass> list = new ArrayList<myclass>();
myclass mc = new myclass();
mc.id=1;
mc.count=20;
mc.value="my value 1"
list.add(mc);
//add 100 record in list
//how can i this
int index = list.find(value="search value");
//or this
myclass founded = list.find(value="search value");
//or this
myclass founded2 = list.where(a => a.value="search value").first; //yes this is linq and lambda, but i cant linq in android
}
if I use for loop, I can find index but maybe arraylist has 1billion over record and I search 1000 values in arraylist
I dont want to use 1000 times for-loop in arraylist.
how can I this basicly
You can use indexOf()
int index = list.indexOf(object)
So if you want to find 1000 values inside your 1billion ArrayList record it is better not to use ArrayList here.
More preferable way for doing that is using HashMap<String, YourClass>.
Where first parameter is your id and second is element of your class.
You can easily found then element of your class by id. Approximately O(1).
If it is no matter how your values will be stored in ArrayList you can implements comparable interface in your class and support your collection in sorted way. So if your collection is sorted you can find your element with binary search.
You should use this version of binary search
Collections.binarySearch(List<? extends T> list, T object, Comparator<? super T> comparator)
So you can implement you custom compator to check if your object is equal to something that you are finding.

How do I store multiple values in an array in Android?

For this example I have an array:
String[] books = new String[x];
I would like to store the id and title in each location:
books[0]=>id:0, title:"book title1"
books[0]=>id:1, title:"book title2"
books[0]=>id:2, title:"book title3"
books[0]=>id:3, title:"book title4"
I want to store the id since it may change. I'm getting the id and title from a database. Getting the info isn't the issue. I want to store it this way so in my other functions this returns to I can use something like:
btn.setText(regions[i].title)
Any suggestion on how to handle this would be great.
Do one thing, first create a bean class like BookBean.
Under this declare two variables ID and Title. and declare getters and setters (If u are using eclipse u can easily do this by (Source -> generate getters and setters.. option)
and then declare a ArrayList to store BookBean vale as of follow.
ArrayList<BookBean> bookArrayList=new ArrayList<BookBean>();
for(int i=0;i<=urSize;i++)
{
// create a object for BookBean
BookBean book =new BookBean();
book.setID("what ever");
book.setTitle("what ever");
bookArrayList.ass(book)
}
It is better to use Arraylist with custom class.
see this
class Book
{
String id,title;
/* Cunstructor to store data */
public Book(String id,String title)
{
this.id = id;
this.title = title;
}
}
//declare arraylist
ArrayList<Book> bookList = new ArrayList<Book>();
bookList.add("1","book1");
bookList.add("2","book2");
bookList.add("3","book3");
bookList.add("4","book4");
btn.setText(bookList.get(i).title)
I think you have several options
Use a HashMap where you can use your id as key and value title
Define a class and keep id and title as attributes , define get and set methods.
Keep the objects of the class in a ArrayList

is there anyway i can have listarray<string,int,int> in android?

is there anyway i can have multi dimensional array ex: listarray string,int,int in android??
it is quite possible with Map & Set in Java/C++.
Make your own container with fields good explaining its purpose:
class PersonData {
public int age;
public int id;
public String name }
And make list of it:
List<PersonData> dataList = new ArrayList<PersonData>();
Acces your fields by:
dataList.get(5).age = 11;
As Egor said in comment, a good practice will be set those field as protected and create setters and getters, if you don't need extreme performance in this specific case.

Categories

Resources