ArrayList and connection different classes - java

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");
}

Related

Using a Java For-Each Loop to iterate over an ArrayList which has private access?

I have three classes: Labradors, Kennels and Show. The Kennel contains a private ArrayList of
Labradors. As shown:
Labradors.java:
public class Labradors {
private String name;
private String description;
public Labradors(String n, String d) {
name = n;
description = d;
}
public String getName() {
return name;
}
}
Kennel.java:
import java.util.ArrayList;
public class Kennel{
private ArrayList<Labradors> labs;
public Kennel() {
labs = new ArrayList<Labradors>();
}
public void addDog(Labradors l) {
labs.add(l);
}
}
and
Show.java
class Show
{
public static void main(String args[])
{
Labradors Dave = new Labradors("Dave", "Good dog!");
Labradors Bob = new Labradors("Bob", "Likes tummy rubs!");
Kennel niceHome = new Kennel();
niceHome.addDog(Dave);
niceHome.addDog(Bob);
for (Labradors lab: niceHome.labs ) {
System.out.println(lab.getName());
}
}
}
My for-each loop in Show gives me the following error:
Show.java:12: error: labs has private access in Kennel
for (Labradors lab: niceHome.labs ) {
^
1 error
Clearly one solution would be to make the ArrayList public, but my understanding of encapsulation is that best practice means it should be private and a Getter written. But how do I do this?
I feel this should have a really easy answer, but I'm having difficulty tracking it down...
NB - I'm using openjdk version 11.0.6 on Ubuntu 19.10.
Inside Kennel Class make a getter function
import java.util.ArrayList;
public class Kennel{
private ArrayList<Labradors> labs;
public Kennel() {
labs = new ArrayList<Labradors>();
}
public void addDog(Labradors l) {
labs.add(l);
}
public ArrayList<Labradors> getLabs(){
return this.labs;
}
}
Then access from main function like this
class Show
{
public static void main(String args[])
{
Labradors Dave = new Labradors("Dave", "Good dog!");
Labradors Bob = new Labradors("Bob", "Likes tummy rubs!");
Kennel niceHome = new Kennel();
niceHome.addDog(Dave);
niceHome.addDog(Bob);
for (Labradors lab: niceHome.getLabs()) {
System.out.println(lab.getName());
}
}
}

Global Variable appending multiple copies of data while updating

I have created a class named "Global Services" which I use to save my data globally and access them in a different activity. But when I am calling the set() method, instead of overview the existing data instead it is appending that data. Below is my code.
I have even tried to remove the instance but still, it is appending the new data instead of overwriting.
import java.util.ArrayList;
import java.util.List;
public class GlobalServices {
private static GlobalServices instance;
String partner, leadsResponse;
List<Leads> assignedList = new ArrayList<>();
List<Leads> unAssignedList = new ArrayList<>();
List<Inventory> listInventory = new ArrayList<>();
private GlobalServices() {}
public static GlobalServices getInstance() {
if (instance == null) {
instance = new GlobalServices();
}
return instance;
}
public static void destory() {
instance = null;
}
public String getPartner() {
return partner;
}
public String getLeadsResponse() {
return leadsResponse;
}
public List<Leads> getAssignedList() {
return assignedList;
}
public List<Leads> getUnAssignedList() {
return unAssignedList;
}
public List<Inventory> getListInventory() {
return listInventory;
}
public void setPartner(String partner) {
this.partner = partner;
}
public void setLeadsResponse(String leadsResponse) {
this.leadsResponse = leadsResponse;
}
public void setAssignedList(List<Leads> assignedList) {
this.assignedList = assignedList;
}
public void setUnAssignedList(List<Leads> unAssignedList) {
this.unAssignedList = unAssignedList;
}
public void setListInventory(List<Inventory> listInventory) {
this.listInventory = listInventory;
}
}
The problem is that you're just assigning new references to your lists in GlobalServices but not creating new lists. This means as soon as you modify this reference from another place in your code, it will be reflected in the GlobalServices list as well. All you have to do is:
public void setAssignedList(List<Leads> assignedList) {
this.assignedList = new ArrayList<>(assignedList);
}
public void setUnAssignedList(List<Leads> unAssignedList) {
this.unAssignedList = new ArrayList<>(unAssignedList);
}
public void setListInventory(List<Inventory> listInventory) {
this.listInventory = new ArrayList<>(listInventory);
}
This way a new copy will be created in memory for each list and the data will be overwritten.
Sorry if I was wrong, but your code here is not a problem.
The problem might come from other part of your application.
The data you set might be the data that extend your current data.
Example you have
GlobalServices instance = GlobalServices.getInstance()
List<Inventory> listInventory1 = new ArrayList<>();
listInventory1.add(new Inventory());
instance.setListInventory(listInventory1); // now your inventory have one item
// In some where else in your project
List<Inventory> listInventory2 = instance.getListInventory(); // lisInventorys.size() equals 1
// Then you add more data to listInventory2 by mistake
listInventory2.add(new Inventory()); // listInventory2.size() equals 2
// Then you set back listInventory2 to your global service
instance.setListInventory(listInventory2); // now your inventory have two item
So, the data had been actually overwrite, it data just been extended by accident.

How to set a value on a class using another class that is called/set in main class

I have 3 classes, say: ShareType, ShareTypesTrue and Main.
public class ShareType {
public String shareTypeName = "";
public String noOfShare = "";
public String parValue = "";
public void setShareTypeName(String shareTypeName) {
this.shareTypeName = shareTypeName;
}
public void setNoOfShare(String noOfShare) {
this.noOfShare = noOfShare;
}
public void setParValue(String parValue) {
this.parValue = parValue;
}
}
public class ShareTypesTrue {
public List<ShareType> shareType;
public void setShareType(List<ShareType> shareType) {
this.shareType = shareType;
}
}
public class Main {
ShareTypesTrue sharetypetrue = new ShareTypesTrue();
sharetypetrue.add(shareTypeName);
}
Now my problem is i need to set shareTypeName to a value under the class ShareTypesTrue. Meaning i have to use ShareTypesTrue to call on the Sharetype class and set the shareTypeName.
Anyone has an idea?
NOTE: I cant change/add code in the first 2 classes except in main. i just need to find a way to get around this.
Thanks Alot
Please check below code for Main class.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String args[]){
ShareTypesTrue sharetypetrue = new ShareTypesTrue();
//Create object
ShareType shareType = new ShareType();
shareType.setShareTypeName("Original Name");
//Create list
List<ShareType> shareTypes=new ArrayList<ShareType>();
shareTypes.add(shareType);
//Attach it to share
sharetypetrue.setShareType(shareTypes);
//Print
for(ShareType shareTypesMember:sharetypetrue.shareType){
System.out.println(shareTypesMember.shareTypeName);
}
//Editing it.
for(ShareType shareTypesMember:sharetypetrue.shareType){
shareTypesMember.shareTypeName = "Updated Name";
}
//Print
for(ShareType shareTypesMember:sharetypetrue.shareType){
System.out.println(shareTypesMember.shareTypeName);
}
}
}
Use Sharetype class to set the shareTypeName
ShareType share = new ShareType();
share.setShareTypeName("name");
share.setNoOfShare("no");
share.setParValue("val");
List<ShareType> shareType = new ArrayList<ShareType>();
shareType.add(share);
use ShareTypesTrue to set Sharetype
ShareTypesTrue sharetrue = new ShareTypesTrue();
sharetrue.setShareType(shareType);//pass ShareType as list
If you want to set the 'name' in ShareType, what prevents you from doing the below:
class ShareTypeTrue_Extended extends ShareTypeTrue{
protected shareTypeName;
public ShareTypeTrue_Extended(String shareTypeName){this.shareTypeName=shareTypeName;}
public void setShareType(List<ShareType> shareType) {
for(ShareType s: shareType)s.setShareTypeName(this.shareTypeName);
super.setShareType(shareType);
}
}

Arraylist add object by setter

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);

Simple caching in Java using hashmap

Just want to use java hashmap to cache a simple pair into memory and want to get the cached data in another instance.
I am using the below code to put some datas into cache consider the below ProcessDefinitionJavaCode.java code.
package Folder.ProcessDefinition;
import java.util.*;
import java.io.*;
public class ProcessDefinitionJavaCode{
/****** START SET/GET METHOD, DO NOT MODIFY *****/
protected String string_1 = "";
protected String string_2 = "";
public String getstring_1() {
return string_1;
}
public void setstring_1(String val) {
string_1 = val;
}
public String getstring_2() {
return string_2;
}
public void setstring_2(String val) {
string_2 = val;
}
/****** END SET/GET METHOD, DO NOT MODIFY *****/
public ProcessDefinitionJavaCode() {
}
public void invoke() throws Exception {
/* Available Variables: DO NOT MODIFY
In : String string_1
In : String string_2
* Available Variables: DO NOT MODIFY *****/
HashMap<Integer,String> cache = new HashMap<Integer,String>();
cache.put(21, "Twenty One");
cache.put(31, "Thirty One");
}
}
What should I be doing If I want to get the datas I added just now in cache
in another java class temp.java.
I am sorry if it is very silly, I am not a Java expert..
You pass the cache Hashmap to the other class in a constructor or a setter method.
HashMap<Integer,String> cache = new HashMap<Integer,String>();
cache.put(21, "Twenty One");
cache.put(31, "Thirty One");
NewClass newClass = new newClass(cache);
or
NewClass newClass = new newClass();
newClass.setCache(cache);
How about this simple approach (it may be not exactly what you want, but you may get an useful idea):
class PairOfStrings {
final String a, b;
PairOfStrings(String a, String b) {
this.a = a;
this.b = b;
}
#Override
public String toString() {
return "PairOfStrings{" +
"a='" + a + '\'' +
", b='" + b + '\'' +
'}';
}
}
class Sample {
public static void main(String[] args) {
HashMap<Integer, PairOfStrings> pairs = new HashMap<Integer, PairOfStrings>();
pairs.put(1, new PairOfStrings("first", "second"));
pairs.put(2, new PairOfStrings("third", "fourth"));
System.out.println(pairs.get(1));
}
}
The only method I know to retrieve the values from a map is creating a function to do so.
That way you can create a function like this:
String[] getValues(){
String[] aux=new String[cache.size()];
int i=0;
for (Integer integer : cache.keySet()) {
aux[i++]=cache.get(integer);
}
System.out.println(Arrays.toString(aux));
return aux;
}

Categories