Reputation: 3
I found a class declaration that works for me, but I wonder if this class could be written more "short":
public class Data implements Comparable <Data>{
public Data (int category, String quality, String title ) {
super();
this.category = category;
this.quality = quality;
this.title = title;
}
int category;
String quality;
String title;
@Override
public int compareTo(Data d) {
return this.getDuration_value() - (d.getDuration_value());
}
}
Why do I have to mention "category, quality an title" this often ? And why "super()" ? I would like to have it just shorter. I found other explanations, but nowhere this "complex structure".
The "data" is given by these lines, and I want that I do not have to declare in advance the length of the array:
Data[] myDataArray = {
new Data(0, // category "0"
"***", // quality
"MyTitle1") // title
new Data(0, // same category "0"
"**", // quality
"MyTitle2") // title
}
Upvotes: 0
Views: 78
Reputation: 1414
super()
invokes the parent class constructor. If you skip this, Java will invoke the default constructor (with no arguments) automatically, so you can skip this line in your example.
Array's length should be declared in advance. If this is a problem, you should use a container such as ArrayList instead. ArrayList
will automatically resize when needed.
As for mentioning the fields multiple times, Java is just this verbose.
Upvotes: 1
Reputation: 10278
The example you provide implements Comparable
which is only necessary if you want to compare your data objects (e.g. is "Obj A" greater than "Obj B" using a comparator). You do not need the constructor. It only exists to ensure your elements are initialized. Otherwise you may end up with NullPointerExceptions and you can't compare.
This example simply is "safe" and can prevent some kinds of problems.
If you just need a "list" you can use ArrayList<Data>
or other List
options.
Upvotes: 0