I have created ArrayList and make setter and getter for it.
In the other class i want to add objects in this array. But my code doesn't works. i think i need to add in method setter for array some other code..
public class DataVar {
private ArrayList<String> arrayLinks = new ArrayList<>();
public ArrayList<String> getArrayLinks() {
return arrayLinks;
}
public void setArrayLinks(ArrayList<String> arrayLinks) {
this.arrayLinks = arrayLinks;
}
}
//Here is another class
public class LinksAd {
public void getAllLinksAd() {
DataVar dataVar = new DataVar();
String link = "href";
dataVar.setArrayLinks(link) }}
Looking at your code you are trying to add a String type, where your code specifies that you are expecting an ArrayList. Assuming you just want to add a string to your arraylist the following will work:
public void setArrayLinks(String arrayLinks) {
this.arrayLinks.add(arrayLinks);
}
You can implement generic setter method.
This is DataVar class:
public class DataVar {
private List<String> itemList=new ArrayList<String>();
public List<String> getItemlist() {
return itemList;
}
public void setItemList(Object list) {
if (list.getClass().equals(String.class)) {
itemList.add((String)list);
}
else if (list.getClass().equals(ArrayList.class)) {
itemList = (ArrayList<String>)list;
}
else {
throw new Exception("Rejected type- You can set String or ArrayList");
}
}
}
And this is calling setter method example:
Main class:
public static void main(String[] args) {
List<String> exampleList = new ArrayList<String>();
exampleList.add("This example");
exampleList.add("belongs to");
String owner = "http://www.javawebservice.com";
DataVar dataVar = new DataVar();
dataVar.setItemList(exampleList);
dataVar.setItemList(owner);
for(String str:dataVar.getItemlist()){
System.out.println(str);
}
}
Output:
This example
belongs to
http://www.javawebservice.com
So, you can set ArrayList, also you can set String.
You could do a mehtod to add an Item like this:
public void addStringToList(String s)
{
arrayLinks.add(s);
}
In LinksAd you have to wirte:
dataVar.addStringToList(link);
Related
I am a newbie to Java and I have a gui class which has a GUI component and it takes the input from the text field and should pass it to another class. The action listener of the button is below.
public void actionPerformed(ActionEvent action) {
arraylist.add(textField_1.getText());
arraylist.add(textField_2.getText());
arraylist.add(textField_3.getText());
arraylist.add(textField_4.getText());
}
since it is a void method I cannot return the array list so that Ii cannot construct a getter.
public ArrayList<String> getList(){
return this.arraylist;
}
Could anyone please tell me how to access this arraylist from the another class without passing it through the constructor? I am sorry if i asked anything wrong. Thanks in advance.
This is one of the many possible approaches.
Just define another class and call the setter from your actionPerformed(..) method.
public class YourOtherClass {
private static ArrayList<String> arraylist;
public void setList(arrayList) {
this.arraylist = arraylist;
}
public ArrayList<String> getList() {
return this.arraylist;
}
}
Now you can simply set this arraylist as:
public void actionPerformed(ActionEvent action) {
arraylist.add(textField_1.getText());
arraylist.add(textField_2.getText());
arraylist.add(textField_3.getText());
arraylist.add(textField_4.getText());
YourOtherClass.setList(arraylist);
}
Now when you want to access the contents of this list, simply use:
...
//any other method
ArrayList<String> arraylist = YourOtherClass.getList();
System.out.println(arraylist.get(0)); //or whatever
...
You can make that arraylist as Static and access it.
To access that particular arraylist use the below syntax
classNameThatContainArraylist.yourArrayList
be careful while using static.
If you want to use to set and get data then there are many approaches and two of them are follow
public class SetDataInArrayList {
//Aproach one by using object
private List<ActionEvent> list;
public SetDataInArrayList() {
list = new ArrayList();
}
public void setDataInList(ActionEvent e) {
list.add(e);
}
public List<ActionEvent> getList() {
return list;
}
//Approach two by using static reference
private static List<ActionEvent> newList;
static {
newList = new ArrayList<>();
}
public static void add(ActionEvent e) {
newList.add(e);
}
public static List<ActionEvent> returnList() {
return newList;
}
if you use either of approach you will need reference variable in both of cases to fetch data
If I understood, you want to do it:
public class A {
private ArrayList<String> arrayList;
public ArrayList<String> getArrayList() {
return this.arrayList;
}
}
public class B {
private A a = new A();
public void actionPerformed(ActionEvent action) {
a.getArrayList().add(textField_1.getText());
a.getArrayList().add(textField_2.getText());
a.getArrayList().add(textField_3.getText());
a.getArrayList().add(textField_4.getText());
}
}
How can I access list of one class in another class using Java.
I'm getting an empty list by using the following code.
My code :
public class DataRead {
public static List<String> list = new ArrayList<String>();
public void readData() {
list.add("abc");
list.add("xyz");
}
}
public class GetListData {
public static void main(String[] args) {
List<String> getList = DataRead.list;
System.out.println(getList); //getting null
}
}
My edited code:
public class GetListData {
public static void main(String[] args){
DataRead dataRead = new DataRead();
dataRead.readData(); //Add elements to list
List<String> myList = DataRead.list;
System.out.println(myList.get(0));
}
}
Still getting empty set after editing the code.
You need to actually call readData() method first, which fills your List, e.g.
public static void main(String[] args) {
new DataRead().readData();
List<String> getList = DataRead.list;
System.out.println(getList);
}
After OP's edit:
I doubt you're getting an empty result - check it out on ideone.
The problem is that, the list is still empty. To read from the list, you need to get specific element out from it:
list.get(x); //where x is an int value
The reason the list has no elements added is because the statements for adding into the list resides in readData method. You need to invoke the method first:
DataRead dataRead = new DataRead();
dataRead.readData();
So to read the elements, you can go with this:
public static void main(String[] args){
DataRead dataRead = new DataRead();
dataRead.readData(); //Add elements to list
List<String> myList = DataRead.list;
System.out.println(myList.get(0)); //getting "abc"
}
If list is not meant to be shared, but as a property of individual DataRead object, I would do it as:
class DataRead
{
//Your other attributes..
private List<String> list;
public DataRead(){
list = new ArrayList<String>();
}
public <ArrayList> getList(){
return list;
}
public void addToList(String s){
list.add(s);
}
}
Change your code to this.
public class DataRead {
public List<String> list;
public void DataRead() {
list = new ArrayList<String>();
list.add("abc");
list.add("xyz");
}
}
And use it as follows.
public class GetListData {
public static void main(String[] args) {
DataRead d = new DataRead();
List<String> getList = d.list;
System.out.println(getList); //getting null
}
}
The best approach would be to use Getters and setters and do not make the variables static, unless and until its required.
Im pretty new to Java. I'm trying to connect these classes together. The Go class, is the main class, that should end up running the program. According to Eclipse, the program doesn't contain any errors, but while running, the outprint is blank.
The Go class:
public class Go {
public static void main(String[] args) {
Data klasseObject = new Data();
klasseObject.infoListe();
}
}
The Ansat class:
import java.util.ArrayList;
public class Ansat {
public String navn;
public int alder;
public Ansat(String navn, int alder, ArrayList<Ansat> ansat){
this.navn = navn;
this.alder = alder;
}
public int getAlder() {
return alder;
}
public void setAlder(int alder) {
this.alder = alder;
}
public String getNavn() {
return navn;
}
public void setNavn(String navn) {
this.navn = navn;
}
}
The Data class:
import java.util.ArrayList;
public class Data {
private ArrayList<Ansat> ansat;
public void infoListe(){
ansat = new ArrayList<Ansat>();
ansat.add(new Ansat("Hej", 123, ansat));
}
public ArrayList<Ansat> getAnsat() {
return ansat;
}
}
Output the contents of ArrayList to console
public class Go {
public static void main(String[] args) {
Data klasseObject = new Data();
klasseObject.infoListe();
for(Ansat ansat : getAnsat()){
system.out.println(ansat.getNavn(), ansat.getAlder());
}
}
}
I recommend just two modifications for you to get a proper readable output.
Add the following method to your Ansat class
//modify the returned string however you want it to appear
public String toString() {
return navn + " , " + alder;
}
and then add this line in your main method of Go class (last statement)
System.out.println(klasseObject.getAnsat().get(0).toString());
The toString() class that is added to the Ansat is overriding the toString() method for Ansat meaning that it allows you to print the fields of Ansat class the way you want it and whenever you invoke toString() on object of Ansat then it will pretty print it for you such as below:
Hej , 123
You can update the toString() method to print it however you want.
If you wish to have more than one element in your ArrayList then you have to do the following changes (but, I do want state that you are not doing this the right way):
Data klasseObject = new Data();
klasseObject.infoListe();
Data klasseObject2 = new Data();
klasseObject.infoListe();
Data klasseObject3 = new Data();
klasseObject.infoListe();
for(Ansat s: klasseObject.getAnsat())
System.out.println(s.toString());
And this changes to your Data class
public void infoListe(){
if(ansat != null) {
ansat.add(new Ansat("Hej", 123, ansat));
} else {
ansat = new ArrayList<Ansat>();
ansat.add(new Ansat("Hej", 123, ansat));
}
}
If I were to review your code and suggest improvements, then I would do the following changes in your classes (copy/paste the following code Go.java file and run it):
import java.util.ArrayList;
public class Go {
public static void main(String[] args) {
// running below creates an ArrayList<Ansat> that is inside KlasseObject
Data klasseObject = new Data();
// creates one Ansat(Hey,123) and add it to list
klasseObject.setData("Hey", 123);
// creates one Ansat(Raf,555) and add it to list
klasseObject.setData("Raf", 555);
// creates one Ansat(X-men,999) and add it to list
klasseObject.setData("X-men", 999);
//as many classes as you want, it would add them all to the list
//of klasseObject
// now that we set three Ansats, we will retrieve the list and print
// them all
for (Ansat s : klasseObject.getAnsatList())
System.out.println(s.toString());
}
}
class Ansat {
public String navn;
public int alder;
//remove the array list from constructor, not needed
public Ansat(String navn, int alder) {
this.navn = navn;
this.alder = alder;
}
public int getAlder() {
return alder;
}
public void setAlder(int alder) {
this.alder = alder;
}
public String getNavn() {
return navn;
}
public void setNavn(String navn) {
this.navn = navn;
}
//overrided toString method to pretty-print Ansat object
public String toString() {
return navn + " , " + alder;
}
}
class Data {
private ArrayList<Ansat> ansat;
// added the constructor for Data to initialize Data with empty list
public Data() {
ansat = new ArrayList<Ansat>();
}
//replaced infoListe to setData and added args to it so you can
//pass them from main method
public void setData(String name, int age) {
// every time setData is called a new Ansat is added to list
Ansat a = new Ansat(name, age);
ansat.add(a);
}
public ArrayList<Ansat> getAnsatList() {
return ansat;
}
}
Actually the process what you have followed is perfectly correct,But your getting blank because your not printing the arraylist, hence your getting blank output. Just add the below line and you will see the correct output.
public void infoListe(){
ansat = new ArrayList<Ansat>();
ansat.add(new Ansat("Hej", 123, ansat));
System.out.println(ansat);
}
or in the main function just use it like this...
public static void main(String[] args) {
Data klasseObject = new Data();
klasseObject.infoListe();
System.out.println(klasseObject.getAnsat());
}
Even iterating over array list will fetch you the output -
for (Ansat ansatLoop : klasseObject.getAnsat()) {
System.out.println(ansatLoop.getAlder() + ":"
+ ansatLoop.getNavn());
}
I hope this would solve your query.
Your code is working Perfectly! It has no
System.out.println();
anywhere in the methods that run.
If you modify the method infoListe() to add a println it will print something out
public void infoListe(){
ansat = new ArrayList<Ansat>();
ansat.add(new Ansat("Hej", 123, ansat));
System.out.println("Element Added to ArrayList");
}
From reading tutorials and practicing Java, I have come across a problem. I have created a String ArrayList, added string to it. However I want one method which allows me to add more string to this arrayList and another method which allows me to display this arrayList. below is my attempt to solve this problem. My code only prints an empty Array List
class apples {
public static void main(String[] args) {
viewArrayList(); //prints a empty arraylist
}
public static void addString() {
ArrayList<String> destinationArray = new ArrayList<String>();
destinationArray.add("example1");
destinationArray.add("example2");
}
static ArrayList GetArrayList() {
ArrayList<String> destinationArray = new ArrayList<String>();
return destinationArray;
}
public static void viewArrayList() {
System.out.println(GetArrayList());
}
}
Didn't you forget adding addString() to getArrayList()?
Your variable destinationArray is declared in a method, it meens that it only exists inside this method outside addString() the object does not exist anymore and you can't access it in other methods. To do it you have to declare it as a class variable like that :
class apples{
ArrayList<String> destinationArray = new ArrayList<String>();
public static void main(String[] args)
When your program is executed, in fact it executes the main method, as a result if you want to execute your method addString() you will have to call it in the main function. It will look like that :
public static void main(String[] args)
{
this.addString();
this.viewArrayList(); //prints a empty arraylist
}
Create a Object of a ArrayList and pass reference to different methods. Example create a ArrayList Object in main class and pass it to addString & display method.
public static void main(String[] args){
List<String> destinationArray = new ArrayList<String>();
viewArrayList(destinationArray);
displayArrayList(destinationArray);//prints a empty arraylist
}
public static void addString(List destinationArray ){
destinationArray.add("example1");
destinationArray.add("example2");
}
...
I would do something like this:
class apples
{
private ArrayList<String> array = new ArrayList<String>();
public void addString(String addString)
{
this.array.add(addString);
}
public ArrayList<String> GetArrayList()
{
return array;
}
}
One problem is that you use a different array list for each method. Every time you use the keyword new you are creating a new (and empty) list.
At the top of your class create the ArrayList once...
private ArrayList<String> myList = new ArrayList<String>();
then refer to myList in all your other methods without assigning it a new value.
public ArrayList<String> getArrayList() {
return myList;
}
public void addSomeStrings() {
myList.add("Some String");
myList.add("Some Other String");
}
and don't be afraid to walk through a Java tutorial. This is a fundamental concept and you may get pretty frustrated if you don't shore up your foundation.
Compile and run following program.
import java.util.ArrayList;
class Apples {
static ArrayList<String> destinationArray = new ArrayList<String>();
public static void main(String[] args) {
System.out.print("First time");
viewArrayList();
addString("Example1");
addString("Example2");
addString("Example3");
System.out.print("Second time");
viewArrayList();
addString("Example4");
addString("Example5");
System.out.print("Third time");
viewArrayList();
}
public static void addString(String example) {
destinationArray.add(example);
}
static ArrayList getArrayList() {
return destinationArray;
}
public static void viewArrayList() {
System.out.println(getArrayList());
}
}
The scope of the array object is the problem here. You are adding string to 1 array and trying to print another array. Remove the static block and the array declaration in addString(). Declare the array next to the class definition like this,
class apples {
ArrayList destinationArray = new ArrayList();
.. ....
It should work.
Code:
public class Apples {
public static void main(String[] args) {
viewArrayList(); //prints a empty arraylist
}
public static ArrayList<String> addString() {
ArrayList<String> destinationArray = new ArrayList<String>();
destinationArray.add("example1");
destinationArray.add("example2");
return destinationArray;
}
public static ArrayList<String> GetArrayList() {
return addString();
}
public static void viewArrayList() {
System.out.println(GetArrayList());
}
}
Output:
[example1, example2]
I'm trying to fill a jComboBox with objects. I have it working in one class, but in this class it's giving a NullPointerException but the code is almost the same. What am I missing here?
The code I'm using to fill the comboboxes:
I have translated every variable to English and removed some unnescessary stuff. I hope it's more clear for you guys now:
package unive.billing.boundary.clientmanager.frames;
import unive.billing.control.ClientsManager;
import unive.billing.control.InsuranceManager;
/**
*
* #author Forza
*/
public class ClientFrame extends javax.swing.JFrame {
/**
* Creates new form AddClientGUI
*/
private ClientsManager clientmanager;
private InsuranceManager insurancemanager;
public ClientFrame() {
initComponents();
clientmanager = new ClientsManager();
clientmanager.printList();
updateComboBoxCompany();
updateComboBoxInsurance();
}
private ClientsManager clientmanager;
private InsuranceManager insurancemanager;
public ClientFrame() {
initComponents();
clientmanager = new ClientsManager();
clientmanager.printList();
updateComboBoxCompany();
updateComboBoxInsurance();
}
public void updateComboBoxCompany()
{
for (Object object : insurancemanager.getCompanyNames())
{
companyComboBox.addItem(object);
}
}
public void updateComboBoxInsurance()
{
for (Object object : insurancemanager.getPolicyNames())
{
insuranceComboBox.addItem(object);
}
}
Here are the methods used:
public Object[] getCompanyNames()
{
ArrayList<String> cnames = new ArrayList<String>();
for (InsurancesCompany company : insurancecompanyList)
{
cnames.add(company.getCompanyName());
}
return cnames.toArray();
}
public Object[] getPolicyNames()
{
ArrayList<String> vnames = new ArrayList<String>();
for (Insurance insurance : insuranceList)
{
vnames.add(insurance.getPolicyName());
}
return vnames.toArray();
}
This is how my lists are initialized:
public class InsuranceManager {
private String insurancePath;
private String insurancecompanyenPath;
private static List<InsurancesCompany> insurancecompanyList;
private static List<Insurance> insuranceList;
private Insurance currentInsurance;
public InsuranceManager() {
insurancecompanyenPath = "Files/company.txt";
insurancePath = "Files/insurance.txt";
insuranceList = new List<>();
}
public void createNewList()
{
insurancecompanyList = new List<>();
System.out.println("Creates list");
}
public Object[] getCompanyNames()
{
ArrayList<String> cnames = new ArrayList<String>();
for (InsurancesCompany company : insurancecompanyList)
{
cnames.add(company.getCompanyName());
}
return cnames.toArray();
}
public Object[] getPolicyNames()
{
ArrayList<String> vnames = new ArrayList<String>();
for (Insurance insurance : insuranceList)
{
vnames.add(insurance.getPolicyName());
}
return vnames.toArray();
}
Edit: Here's the MainGUI which calls createNewList (maakLijstAan)
private ClientsManager clientsmanager;
private BillingManager billingmanager;
private InsuranceManager insurancemanager;
public MainGUI() {
clientsmanager = new ClientsManager();
clientsmanager.CreateNewList();
insurancemanager = new InsuranceManager();
insurancemanager.CreateNewList();
insurancemanager.loadInsuranceCompanyList();
initComponents();
jMenuItem1.setText("Save clients");
jMenuItem2.setText("Load clients");
jMenuItem3.setText("Exit");
}
You never initialize verzekeringBeheer, therefore you get a NullPointerException when you try to invoke methods on that variable.
You should have somewhere in your constructor, something like this:
verzekeringbeheer = new VerzekeringBeheer();
Also, try to avoid making your code coupled with other parts of your code. For example:
public VerzekeringBeheer() {
...
//verzekeringmaatschappijLijst is never initialized!!!
}
public void maakLijstAan()
{
verzekeringmaatschappijLijst = new Lijst<>();
System.out.println("Maak lijst aan");
}
public Object[] getMaatschappijNamen()
{
ArrayList<String> mnamen = new ArrayList<String>();
// Here you use verzekeringmaatschappijLijst without checking that is not null!!!
for (VerzekeringsMaatschappij maatschappij : verzekeringmaatschappijLijst)
{
mnamen.add(maatschappij.getMaatschappijNaam());
}
return mnamen.toArray();
}
If nobody calls maakLijstAan, you will get a NullPointerException in getMaatschappijNamen. Try to avoid code that is so dependent of external code, in order to run without problems.
all data for JComboBox are stored in ComboBoxModel
set ComboBoxModel for proper Objects type (String, Integer, Icon or simple Object), Java7 implements Generics, there are significant differiences in compare with Java6
all updates (to the JComboBox or its Model) must be done on Event Dispatch Thread
I only see you useing variables but for me they are nit initialized. So they are null and you get a NPE.
So how are verzekeringmaatschappijLijst and verzekeringLijst initialized?