How to use a table inside a java class
I need a little help regarding the java code, whenever I came to initialize a table as an attribute in a class, I didn't find the definition logic since no [] is set there, so I'm curious to know with an example of a class that works with an attribute tables, and should I initialize the table in the default constructor with null? So, I did the best I could, but I cannot understand this code that I wrote, and of course there will be many errors:
public class ClasseSMI {
private String _filiereName;
private String[] _etudiantsList;
public ClasseSMI()
{
this._filiereName ="jjjjj";
this._etudiantsList = null;
}
public String toString() {
return _filiereName + " " + _etudiantsList;
}
public static void main(String[] args) {
ClasseSMI smi = new ClasseSMI();
System.out.println(smi);
}
}
so anyone can help with an example please?
Thanks in advance!
source to share
You have just started learning Java. There are so many ways to do what you want to achieve. Initializing zeros is only one way to initialize an array reference. The default, but not the best. Here's what you might want:
public class ClasseSMI {
private String _filiereName;
private String[] _etudiantsList;
public ClasseSMI()
{
this._filiereName ="Alex";
this._etudiantsList = new String[]{"Nick","Mark","Nickole"};
}
public String toString() {
String result=_filiereName+":";
for(String etudiant:_etudiantsList){
result+= " "+ etudiant;
}
return result;
//return _filiereName + " " + _etudiantsList;
}
public static void main(String[] args) {
ClasseSMI smi = new ClasseSMI();
System.out.println(smi);
}
}
It returns
Alex: Nick Mark Nicole
If you use your return it will use defaultString () on the array and it will look like this:
Alex [Ljava.lang.String; @ 17dfafd1
source to share