I have a modest programming background, but I am totally green to Java. I inherited some Java code at work, and I am simply trying to call this list properly.
Assistance appreciated.
public class CallTestClassList {
try { <how do I properly call the list from TestClass?> }
}
public class TestClass {
public List TestList() {
String s = null;
List cData = new ArrayList();
String[] Warning = null;
String[] Error = null;
int flag = 0;
}
return cData;
}
new TestClass().TestList();
At least, that's what I assume is the answer since I don't know what sort of constructors TestClass has.
Related
I'm struggling with an assignment of mine and I can't figure out how to add another element to my list.
import java.util.ArrayList;
public class Ballot {
private ArrayList<Candidate> ballot;
private String officeName;
public Ballot(String officeName) {
this.officeName = officeName;
ArrayList<Candidate> ballot = new ArrayList<Candidate>();
}
public String getOfficeName() {
return officeName;
}
public void addCandidate(Candidate c) {
ballot.add(c);
}
public ArrayList<Candidate> getCandidates() {
return ballot;
}
public static void main(String[] args) {
Ballot b = new Ballot("Election");
b.addCandidate(new Candidate("Sarah", "President"));
System.out.println(b);
}
}
When I try to run the document, it throws a NullPointerException. What am I doing wrong?
The constructor initializes a local variable named ballot that hides the data member with the same name. Then, when you try to add to it, it fails with a NullPointerException, since it was never initialized. If you initialize it you should be OK:
public Ballot(String officeName) {
this.officeName = officeName;
ballot = new ArrayList<Candidate>(); // Here!
}
You're not initializing your list of candidates properly in the Ballot constructor. You need to do:
this.ballot = new ArrayList<Candidate>();
Right now you're just creating a local variable named ballot in the constructor which shadows the actual class field. Since it has never been initialized, you end up getting a NullPointerException when you eventually try to add an element to it.
Also, as a best practice, use interfaces instead of the concrete type. This makes it easy to change implementations later. So instead of defining the field as private ArrayList<Candidate> ballot;, define it as private List<Candidate> ballot;.
As simple that you are not using this object. You are never initiliazing your object
Correct way
public Ballot(String officeName) {
this.officeName = officeName;
this.ballot = new ArrayList<Candidate>();
}
You're overriding your class variable with a local variable of the same name. Either initialize the list directly
private List<Candidate> ballot = new Arraylist<>();
or initialize it in the constructor with
ballot = new ArrayList<>();
FYI: You shouldn't assign implementation classes for your local variables and return values if you can help it. "ballot" should just be the List interface as should the getter. That way if you ever want to change the implementation, you don't have to change everything. It could be an ArrayList, LinkedList, Stack, Vector, etc and it won't matter because they're all using the List interface.
I'm coding an Android app with Firebase and want to write an object to the database:
public class newEvent {
public String whoEv;
public String whereEv;
public String whenEv;
public String whatEv;
public newEvent() {}
public newEvent(String whoEv, String whereEv, String whenEv, String whatEv) {
this.whoEv = whoEv;
this.whereEv = whereEv;
this.whenEv = whenEv;
this.whatEv = whatEv;
}
}
This works, but as you can see they are all 'just' strings. What i want is to have the first argument to be a List, Firebase doesnt allow String[] uploads/writings.
The reason is to be able to pass more names into the whoEv as separated Strings/Objects. (to give each name a boolean if they are coming or not).
Now to the exact problem:
public newEvent(List<String> whoEv, String whereEv, String whenEv, String whatEv) {
this.whoEv = whoEv;
this.whereEv = whereEv;
this.whenEv = whenEv;
this.whatEv = whatEv;
}
When i use this, i have no clue how to write the proper code:
newEvent test = new newEvent(List<String>("derp","max"), "Amsterdam", "31/12/2016", "NewYears Eve");
The above obviously doesnt work. Expression expected or unexpected token. What am i missing or doing wrong? Already thanks for reading this!
Edit: Total idiot idea to use List<String>if i want to pass boolean values with the strings... Dont got clue what to use instead though.
Fixed it:
newEvent test = new newEvent("Meppel", "31/12/2016", "Oudjaarsdag", new String[]{"derp", "Sir", "max"});
And in the class as:
`public class newEvent {
public ArrayList<String> wie;
public String waar;
public String wanneer;
public String wat;
public newEvent() {}
public newEvent(String waar, String wanneer, String wat, String... wie) {
this.wie = new ArrayList<>(Arrays.asList(wie));
this.waar = waar;
this.wanneer = wanneer;
this.wat = wat;
}
List is an Interface, you can't directly use it with out a implementation class. You can use one of default jdk provided classes which implements List interface. example ArrayList, LinkedList.
Go through this link on List Implementations and you will understand how you can pass a list of string as argument.
Is it Java? May be you need add the word "new" before List...
And don't forget List is an interface type, so here need use some inheritance class. ArrayList for example
If you want to get straight to the problem, skip this paragraph. As practice, I am trying to write a Java program that simulates an economy, and to that end wrote a company class. The idea was to have, say, a dozen of them, wrap their earnings into a normalvariate function, and that would be the economy.
I wrote a separate class to graph the companies' outputs using JFreeChart. However, I can't access the ArrayList that I write the amount of money for each year to from the graphing class. I understand the best way to do this is probably with getters, but it didn't seem to work, so if that is your advice, could you please provide an example? Thanks!
The company:
public class ServiceProvider implements Company {
//Variables
public ArrayList getRecords(){
return records;
}
public ServiceProvider(){
money = 10000;
yearID = 0;
goodYears = 0;badYears = 0;
records = new ArrayList();
id++;
}
public void year() {
yearID++;
if(!getBankrupt()){
spend();
}
writeRecords();
}
public void spend() {
...
}
public void printRecords() {
for(int i=0;i<records.size();i++){
String[] tmp = (String[]) records.get(i);
for(String a:tmp){
System.out.print(a+" ");
}
System.out.print("\n");
}
}
public void writeRecords(){
String[] toWrite = new String[2];
toWrite[0] = String.valueOf(yearID);
toWrite[1] = String.valueOf(money);
records.add(toWrite);
}
public void writeRecords(String toWrite){
String temp = "\n"+yearID+" "+toWrite;
records.add(temp);
}
public boolean getBankrupt(){
boolean result = (money < 0) ? true : false;
return result;
}
}
What I am trying to access it from:
public class grapher extends JFrame {
ArrayList records = s.getRecords();
public grapher(){
super("ServiceProvider");
final XYDataset dataset = getCompanyData();
}
private XYDataset getCompanyData(){
XYSeries series;
for(int i=0;i<s.getRecords().length;i++){ //S cannot be resolved, it's instantiated in the main class.
}
}
}
The main class:
public class start {
public static void main(String[] args) {
ServiceProvider s = new ServiceProvider();
for(int i=0;i<10;i++){
s.year();
}
s.printRecords();
}
}
P.S. Don't tell me what a mess Records are. I know.
Pass the instance of ServiceProvider as an argument to the grapher constructor and then it can pass it as an argument to getCompanyData().
Since the instance is created outside of the grapher class, there is no way for grapher to have the instance of ServiceProvider to work with unless you hand that instance to grapher.
BTW, make sure that whatever you do with that ArrayList in grapher that you don't change it. If you do, you'll be changing it in the ServiceProvider (since it's all just references to the same underlying ArrayList). That's probably not what you want to do. If you do need to change it, make a copy and work with the copy.
Your grapher class is trying to use a variable from the start class(you are making calls to variable s which exists in the start class), without having a reference to the variable. In order for grapher to access that instance, you'll have to pass it in to the grapher class as a paramater in the constructor:
public grapher(ServiceProvider serviceProvider) {
records = serviceProvider.getRecords();
}
In the getCompanyData method, use your class variable records instead of s.
Your grapher class should be as follows
public class grapher extends JFrame {
public grapher(ServiceProvider s){
super("ServiceProvider");
final XYDataset dataset = getCompanyData(s);
}
private XYDataset getCompanyData(ServiceProvider s){
XYSeries series;
for(int i=0;i<s.getRecords().length;i++){
// Do Process of business logic.
}
}
}
Let's say I have this:
public class Whatever {
private ArrayList<String> myList = new ArrayList<String>();
// more code goes here
}
or let's say I have this:
public class Whatever {
private ArrayList<String> myList = null;
public Whatever() {
myList = new ArrayList<String>();
}
}
What's the difference between these two initialisations of myList? Would it be wrong to preffer the first variant?
The first variant will always instantiate the array list, the second one only when calling the default constructor. Meaning for the second solution you will have to call the default constructor for any additional constructor you add e.g.
public class Whatever {
private final List<String> myList;
public Whatever() {
myList = new ArrayList<String>();
}
public Whatever(String name) {
this();
// Other stuff done
}
public Whatever(List<String> myList) {
this.myList = myList;
}
}
The (second) "lazy" initialization method might be better if you don't always use the list (e.g. if you set the list in another constructor directly like in my example) and want to avoid creating unnecessary objects. (EDIT: I changed the ArrayList to an interface and set it final. It wasn't part of the question but it is - as mentioned in the comments - the best way to use List collections).
The JVM first executes code such as this (outside the constructor):
public class Whatever {
private ArrayList<String> myList = new ArrayList<String>();
// more code goes here
}
And only then code such as this (inside the constructor):
public class Whatever {
private ArrayList<String> myList = null;
public Whatever() {
myList = new ArrayList<String>();
}
}
So unless the order of execution is somehow important to you i guess #Daff's answer is the right one.
In this particular example, there is no difference except that the first form is shorter.
However, if the attribute initialization expression (potentially) throws exceptions, the second form allows you to catch the exceptions, or declare them as thrown in the constructor signature.
And of course, if you have multiple constructors, the second form allows you to initialize the attribute differently in each constructor ... or use constructor chaining to initialize the attribute the same ... or mix the two styles of initialization.
When calling a method that adds an object to a collection in GWT I get a null pointer error. I have no idea why as everything I have done creates a very simple object (only contains a string). Here is the code that calls the function and the function:
public class PlantMenu extends VerticalPanel {
private Collection<PlantData> plantList;
private Collection<PlantData> newPlantData;
public PlantMenu() {
createPlants();
/*
for(Iterator<PlantData> i = plantList.iterator(); i.hasNext();) {
Window.alert(i.next().getPlantName());
}*/
}
public Collection<PlantData> createPlants() {
PlantData plant1 = new PlantData("Herbs");
PlantData plant2 = new PlantData("Flowers");
PlantData plant3 = new PlantData("Vegetable");
newPlantData.add(plant1);
newPlantData.add(plant2);
newPlantData.add(plant3);
return newPlantData;
}
}
It errors out (null pointer) when trying to add the first plant, this line:
PlantData plant1 = new PlantData("Herbs");
Any help appreciated :)
You didn't initialize your collections. Despite, you already told that its not on that line, but I doubt it. Showing a full exception stack would be much more helpful though. And the exception may occur in your PlantData constructor, but you didn't show it here.
You could do something like this,
private Collection<PlantData> plantList = new ArrayList<PlantData>();
private Collection<PlantData> newPlantData = new ArrayList<PlantData>();
I have used ArrayList, because generally we use ArrayList. Other implementation can also be used, according to the requirements.
You have not initialised your variables properly, this has nothing to do with GWT and is just basic Java. Here's a working version:
public class PlantMenu extends VerticalPanel {
private List<PlantData> plantList = new ArrayList<PlantData>();
private List<PlantData> newPlantData = new ArrayList<PlantData>();
public PlantMenu() {
createPlants();
for(PlantData plant : newPlantData) {
Window.alert(plant.getPlantName());
}
}
public List<PlantData> createPlants() {
newPlantData.add(new PlantData("Herbs"));
newPlantData.add(new PlantData("Flowers"));
newPlantData.add(new PlantData("Vegetable"));
return newPlantData;
}
}
As a side note, you shouldn't be extending VerticalPanel, but rather extending Composite and then using a vertical panel as your widget using setWidget(...);