ok i try to play with arraylist in java awhile to experiment some thing that related my project..so i come up with a simple code like this
having 3 file...DataStruc.java , DataStrucHand.java , testcase1.java
DataStruc.java
public class DataStruc {
private String testString;
public DataStruc(String s){
this.testString = s;
}
public String getTestString() {
return testString;
}
public void setTestString(String testString) {
this.testString = testString;
}
public String toString(){
return String.format("%s",testString);
}
}
DataStrucHand.java
import java.util.ArrayList;
public class DataStrucHand {
private ArrayList<DataStruc> ds;
public void addData(String ss){
ds.add(new DataStruc(ss));
}
public ArrayList<DataStruc> getData(){
return ds;
}
}
testcase1.java
import java.util.*;
public class testcase1 {
public static void main(String args []){
DataStrucHand dsh = new DataStrucHand();
String gdata = "test";
dsh.addData(gdata);
}
}
i tried to compile it and having this error
Exception in thread "main" java.lang.NullPointerException
at DataStrucHand.addData(DataStrucHand.java:7)
at testcase1.main(testcase1.java:8)
can i know what is wrong actually? i cant even add the data...i am trying to add the data and retrieve it back by creating another testcase2.java...but than i having problems in adding now to the arraylist...my purpose is to create a temp storage to keep a specific string that can be obtain by 1 program but runs with 2 different classes..
You never assign anything to the ds field.
DataStrucHand.java
import java.util.ArrayList;
public class DataStrucHand {
private ArrayList<DataStruc> ds; //I am null because nothing is ever new'd up here...
public void addData(String ss){
ds.add(new DataStruc(ss));
}
public ArrayList<DataStruc> getData(){
return ds;
}
}
Try it with this line:
private ArrayList<DataStruc> ds = new ArrayList<DataStruc>();
Or, you can have a constructor that will new it up if you prefer that method:
public DataStrucHand() {
ds = new ArrayList<DataStruc>();
}
You need to put an ArrayList<DataStruc> instance in ds.
You haven't instantiated the ArrayList. Write this:
public class DataStrucHand {
private ArrayList<DataStruc> ds = new ArrayList<DataStruc>();
public void addData(String ss){
ds.add(new DataStruc(ss));
}
You've never initialized ds, so it is null when you call ds.add(new DataStruc(ss)); Add a constructor to DataStrucHand that initializes ds, such as ds = new ArrayList<DataStruc>();.
The problem is that your DataStrucHand class never initializes its private field ds, so when you try to call ds.add(...) it fails with NullPointerException.
In fact, the way the class looks right now, there is no way ds can be anything else than null.
Shortest way to fix this is to initialize ds properly:
private final List<DataStruc> ds = new ArrayList<DataStruc>();
This way each DataStrucHand instance is constructed with an ArrayList inside and ds is never null.
Related
public static class One {
#Override
public String interact(String... values) {
String actualTextOne = "test";
return actualTextOne;
}
}
public static class Two {
#Override
public String interact(String... values) {
String actualTextTwo = "test";
/* Here I need to compare actualTextOne and actualTextTwo, but the problem is that I can't find solluction how to use actualTextOne in Two class*/
return actualTextTwo;
}
}
You cannot do that.
Please check variable scope in java.
https://www.codecademy.com/articles/variable-scope-in-java
A possible solution here is to call the method interact from the class One. Something like this
public static class Two {
#Override
public String interact(String... values) {
String actualTextTwo = "test";
One one = new One();
String actualTextOne = one.interact(values);
// compare values here
return actualTextTwo;
}
}
Why in your classes functions have parameters if you dont use it?
You can mark your class with static only if he is nested, else you need do like this:
class Two {
static public String interact(String... values) {
String actualTextTwo = "test";
return actualTextTwo;
}
}
String textOne = One.interact("");
String textTwo = Two.interact("");
System.out.println(textOne==textTwo);
package com.pr.trio;
import java.util.List;
public class lalala {
private List<SegmentationFieldValue> segmentationFieldValues;
public static class SegmentationFieldValue {
private Integer segmentationFieldId;
private Integer segmentationFieldGroupId;
private String value;
public Integer getSegmentationFieldId() {
return segmentationFieldId;
}
public void setSegmentationFieldId(Integer segmentationFieldId) {
this.segmentationFieldId = segmentationFieldId;
}
public Integer getSegmentationFieldGroupId() {
return segmentationFieldGroupId;
}
public void setSegmentationFieldGroupId(Integer segmentationFieldGroupId) {
this.segmentationFieldGroupId = segmentationFieldGroupId;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
public List<SegmentationFieldValue> getSegmentationFieldValues() {
return segmentationFieldValues;
}
public void setSegmentationFieldValues(List<SegmentationFieldValue> segmentationFieldValues) {
this.segmentationFieldValues = segmentationFieldValues;
}
}
package com.pr.trio;
import java.util.Arrays;
public class kk {
public static void main(String[] args) {
lalala l1 = new lalala();
//currently passed as an empty array, want to set SegmentationFieldId & value here from inner class
l1.setSegmentationFieldValues(Arrays.asList());
//lalala.SegmentationFieldValue.this.setSegmentationFieldId(15);
System.out.println(l1.getSegmentationFieldValues());
}
}
So here, I'm not able to pass values for the segmentation field instead of the empty array, gives an error. So how can I set the values from the inner class fields & pass it to my list?
Seeing as your SegmentationFieldValue class is public, it's trivial to use it inside another class, there are basically two ways to go about this:
The first is to import the inner class:
import com.pr.trio.lalala.SegmentationFieldValue;
The second is to qualify the classname whenever you use it:
lalala.SegmentationFieldValue a = new lalala.SegmentationFieldValue();
You can then call the setters on this class, and use the objects in your call to setSegmentationFieldValues:
lalala.SegmentationFieldValue a = new lalala.SegmentationFieldValue();
a.setSegmentationFieldId(1);
a.setSegmentationFieldGroupId(1);
a.setValue("a");
lalala.SegmentationFieldValue b = new lalala.SegmentationFieldValue();
b.setSegmentationFieldId(2);
b.setSegmentationFieldGroupId(1);
b.setValue("b");
l1.setSegmentationFieldValues(Arrays.asList(a, b));
Judging from your comment code, you also seem to be looking for a shorthand way to add an element to your list. A simple implementation could look like this (in class lalala):
public void addSegmentationFieldValue(Integer id, Integer groupId, String value)
{
if (segmentationFieldValues == null)
{
segmentationFieldValues = new ArrayList<>();
}
SegmentationFieldValue result = new SegmentationFieldValue();
result.setSegmentationFieldId(id);
result.setSegmentationFieldGroupId(groupId);
result.setValue(value);
segmentationFieldValues.add(result);
}
After which you can do the following in the main method of k1:
l1.addSegmentationFieldValue(1, 1, "a");
I just saw this tutorial creating multiple objects using the same instance by applying the DAO pattern and tried it in a simple console, but I always get this message java.lang.NullPointerException I'm now confused, as far as I know, a constructor can be used once only, and the object will be immutable. Kindly look at this:
Fighter.java
public class Fighter {
private String style;
public Fighter() {}
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
}
FightersDAO.java
public class FightersDAO {
public List<Fighter> getFighters(){
List <Fighter> fighter = new ArrayList<>();
String [] styles= { "Karate", "Sumo", "Pro-Wrestling" };
for(int i=0; i < styles.length; i++) {
Fighter temp = new Fighter();;
temp.setStyle(styles[i]);
fighter.add(temp);
}
return fighter;
}
}
Demo.java
public class Demo {
private static FightersDAO fighterDAO;
public static void main (String [] args) {
List <Fighter> fighters = fighterDAO.getFighters();
for(Fighter e: fighters) {
System.out.println(e.getStyle()); //this should output the objects, but nothing shows
}
}
}
Why is it null? What part did went wrong
The variable fighterDAO is never initialized. Therefore you get a NPE here:
List <Fighter> fighters = fighterDAO.getFighters();
To fix that use:
private static FightersDAO fighterDAO = new FightersDAO();
private static FightersDAO fighterDAO;
I think there is a problem because it is not initialized.
Change it:
private static FightersDAO fighterDAO = new FightersDAO();
In your code
private static FightersDAO fighterDAO;// here is not initialized. its just a declaration so fighterDAO = null;
while executing below code will throw exeption
List fighters = fighterDAO.getFighters();// means null.getFighters();
Below is the correct code
package aks;
import java.util.List;
public class Demo {
private static FightersDAO fighterDAO= new FightersDAO();
public static void main (String [] args) {
List <Fighter> fighters = fighterDAO.getFighters();
for(Fighter e: fighters) {
System.out.println(e.getStyle());
}
}
}
You can analyse this by just debuggin on eclise or any IDE
If you want same instance use below code
private static FightersDAO fighterDAO = new FightersDAO();
I have been coding in Java for about a week now but I am still having issues learning it.
I know that we can create a class and then create instance of it by using the name of a class.
but I have this code which is giving me trouble understanding what is happening here,
This is the file called XMLGettersSetters.java,
public class XMLGettersSetters {
private ArrayList<String> title = new ArrayList<String>();
private ArrayList<String> artist = new ArrayList<String>();
private ArrayList<String> country = new ArrayList<String>();
private ArrayList<String> company = new ArrayList<String>();
private ArrayList<String> price = new ArrayList<String>();
private ArrayList<String> year = new ArrayList<String>();
public ArrayList<String> getCompany() {
return company;
}
public void setCompany(String company) {
this.company.add(company);
Log.i("This is the company:", company);
}
public ArrayList<String> getPrice() {
return price;
}
public void setPrice(String price) {
this.price.add(price);
Log.i("This is the price:", price);
}
public ArrayList<String> getYear() {
return year;
}
public void setYear(String year) {
this.year.add(year);
Log.i("This is the year:", year);
}
public ArrayList<String> getTitle() {
return title;
}
public void setTitle(String title) {
this.title.add(title);
Log.i("This is the title:", title);
}
public ArrayList<String> getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist.add(artist);
Log.i("This is the artist:", artist);
}
public ArrayList<String> getCountry() {
return country;
}
public void setCountry(String country) {
this.country.add(country);
Log.i("This is the country:", country);
}
}
Now I can create object of this class like this,
XMLGettersSetters myObject = new XMLGettersSetters();
but from the website where I am learning this code, they have created the objects like this,
public static XMLGettersSetters data = null;
How come the object is declared static ? what does the above code even mean.
Shouldn't it just be,
XMLGettersSetters data = null;
From what I know, when we declare a variable as static then we donot need to instantiate a class to use a static variable from that class.
One more question,
public static XMLGettersSetters getXMLData() {
return data;
}
I have no idea what happened in the above code,
first the object is instantiated as static then instead of giving object a name, a function is given instead which is getXMLData().
And the return type is data
Now about the code below,
public static void setXMLData(XMLGettersSetters data) {
XMLHandler.data = data;
}
A method is created with XMLGettersSetters object as an argument, but what about XMLHandler.data ?
What is it ? shouldn't it be this.data ?
They probably created the object static because they want it to be global. For example, anywhere in the code you will be able to call XMLHandler.data. (I'm supposing here the class in which is created the data variable is XMLHandler because it is used in the setter method..
If it would simply be XMLGettersSetters data = null; instead of static... then it could not be accessed from anywhere in the code.
As for the XMLHandler.data used instead of this.data you have to know that by convention, most of the people specify the class name before the object they are accessing when accessing a static variable.
Static is a field, not an object. Static fields are per class, shared by all code that have access to this field. They are initialized only once, when the class is first loaded. Usual fields (without static) are per object instance. They are initialized when the object instance is created.
In Java, you can assign the value in the same sentence where you declare the variable:
int x = 2;
Object y = new Object().
The object is instantiated, but then placed into a static variable. This means that you always access the same instance of the XMLGettersAndSetters.
As the methods are static you have to refer to a static variable rather than this.data which refers to the variable in the current instance.
I have a class like this
public class TypeUtil {
private static final TypeUtil s_instance = new TypeUtil();
public static TypeUtil getInstance() {
return s_instance;
}
private TypeUtil() {
}
public void metadata() {
// some code here
// and use some_object value here only not in isAlpha
}
public boolean isAlpha(String value) {
}
}
And which I am using to call metadata class like this
TypeUtil util = TypeUtil.getInstance();
util.metadata();
Similarly, I am using above TypeUtil class to call isAlpha method like this -
TypeUtil.getInstance().isAlpha(some_value);
Problem Statement:-
Now what I am trying to do is - I need to pass one object to TypeUtil constructor, and which I need to use in metadata method. With the above code, how can I do that?
Is this ok to do like this? or is there any better way of doing it?
TypeUtil util = TypeUtil.getInstance(some_object);
util.metadata();
And then in the getInstance method of TypeUtil class assign this some_object value to some_variable object?
If yes, then how would I call isAlpha method? Bcoz for that, I don't want to pass any object to the constructor for calling it.
You could add a parameter to metadata() to make it metadata(SomeType name), or just make the TypeUtil constructor public and add a parameter to it:
private final SomeType name;
public TypeUtil(SomeType name) {
this.name = name;
}
Although, considering that you only need some_object for metadata(), I would suggest the first option.
Given my understanding of your question, this is one way of doing what you want to do. Assuming you want your some_object to be static:
public class TypeUtil {
private static final TypeUtil s_instance = new TypeUtil();
private static SomeType some_object = default_Object; // any default value you want
public static TypeUtil getInstance() {
return s_instance;
}
public static TypeUtil getInstance(SomeType some_object) {
this.some_object = some_object;
return s_instance;
}
private TypeUtil() {
}
public void metadata() {
// some code here
// and use some_object value here only not in isAlpha
}
public boolean isAlpha(String value) {
}
}