HashSet loses the old element when adding a new one - java

It is necessary for a HashSet to be defined in one class, and for me to access this HashSet from other classes and add data to it. However, it doesn't go very easily, because every time it's as if the HashSet is reset and when I add a new element, the old one is gone.
Output:
[]
[[sdadsa, fafafsa, ghfhgf, kjhkjh]]
[[], [sdadsa, fafafsa, ghfhgf, kjhkjh]]
First class:
public class listaKlasa {
protected static Set<ArrayList<String>> unikatna = new HashSet<ArrayList<String>>();
public static void setUnikatna(ArrayList<String> ista) {
unikatna.add(ista);
}
public static Set<ArrayList<String>> getUnikatna() {
return unikatna;
}
}
Secund class:
public class novitest {
public static void main(String[] args) {
System.out.println(listaKlasa.getUnikatna());
ArrayList<String> li = new ArrayList<>();
li.add("sdadsa");
li.add("fafafsa");
ArrayList<String> la = new ArrayList<>();
li.add("ghfhgf");
li.add("kjhkjh");
listaKlasa.setUnikatna(li);
System.out.println(listaKlasa.getUnikatna());
listaKlasa.setUnikatna(la);
System.out.println(listaKlasa.getUnikatna());
}
}

The mistake is adding elements, instead of adding 2: 2, you added everything to one list.
First class:
public class listaKlasa {
protected static Set<ArrayList<String>> unikatna = new HashSet<ArrayList<String>>();
public static void setUnikatna(ArrayList<String> ista) {
unikatna.add(ista);
}
public static Set<ArrayList<String>> getUnikatna() {
return unikatna;
}
}
Secund class:
public class novitest {
public static void main(String[] args) {
System.out.println(listaKlasa.getUnikatna());
ArrayList<String> li = new ArrayList<>();
li.add("sdadsa");
li.add("fafafsa");
ArrayList<String> la = new ArrayList<>();
la.add("ghfhgf");
la.add("kjhkjh");
listaKlasa.setUnikatna(li);
System.out.println(listaKlasa.getUnikatna());
listaKlasa.setUnikatna(la);
System.out.println(listaKlasa.getUnikatna());
}
}

Try this:
System.out.println(listaKlasa.getUnikatna());
ArrayList<String> li = new ArrayList<>();
li.add("sdadsa");
li.add("fafafsa");
ArrayList<String> la = new ArrayList<>();
la.add("ghfhgf");
la.add("kjhkjh");

Related

Sort an Object list with Collections having only list as parameter in Java

I have an assignment says printing a object list with given main class:
public static void main(String[] args) throws IOException {
ArrayList<LoaiPhong> ds = new ArrayList<>();
Scanner in = new Scanner(new File("xx.in"));
int n = Integer.parseInt(in.nextLine());
while(n-->0){
ds.add(new LoaiPhong(in.nextLine()));
}
Collections.sort(ds); //this only include object list
for(LoaiPhong tmp : ds){
System.out.println(tmp);
}
}
static class LoaiPhong {
String line;
public LoaiPhong(String line) {
this.line = line;
}
}
So that's mean i have to do something outside the main class to sort the list. Can anyone suggest what to do to sort the object list by its property?
Edit: Thanks to Gus i have the answer, the new class look something like this
static class LoaiPhong implements Comparable<LoaiPhong> {
...
#Override
public int compareTo(LoaiPhong_.LoaiPhong o) {
return <Some logic here>;
}
}

Access List item without waiting for the List to be populated fully

I have a List as per following:
private void someMethod () {
String str= "someStrParam";
private int theCount = 0;
List<String> itemList = getListMethod(str);
if (theCount < itemList.size()) {
return itemList.get(theCount++);
} else {
return null;
}
}
Question: As soon as a List item is added to the List in the getListMethod, how can I access it immediately in the someMethod without waiting for the next item to be added? Or is there way a way we put a monitor on getListMethod so that, as soon as the an item is added there, we can query the itemList ?
You can use the PropertyChangeSupport with your custom list:
class MyList<T> {
private final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
private final List<T> itemList = new ArrayList<>();
public void addName(T name) {
itemList.add(name);
propertyChangeSupport.firePropertyChange("item", null, Collections.unmodifiableList(itemList));
}
public void addPropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.removePropertyChangeListener(l);
}
}
Usage:
public static void main(String[] args) {
MyList<String> myBean = new MyList<>();
myBean.addPropertyChangeListener(evt -> System.out.println("Hello"));
myBean.addName("Hello");
}
To simplify, to test the usage and to understand answer given by #PavlMits, I tried like this:
public class MyListUsage {
public static void main(String[] args) {
MyList<String> myList = new MyList<>();
myList.addPropertyChangeListener(evt -> callThisOnAddItemToList ());
myList.addName("foo");
myList.addName("bar");
myList.addName("blah-blah");
}
private static void callThisOnAddItemToList () {
System.out.println("Do something here as and when an item added to list ......");
}
}
And I got the below output:
Do something here as and when an item added to list ......
Do something here as and when an item added to list ......
Do something here as and when an item added to list ......

Cannot Find Symbol Error when creating an object

I am creating an ArrayList object that contains a class. However, when I call a method from the WordList() class, it says "error: cannot find symbol obj.numWordsOfLength(2)"
import java.util.ArrayList;
public class WordList{
public static void main(String []args){
ArrayList obj = new ArrayList<WordList>();
obj.add("bird");
obj.add("wizard");
obj.add("to");
obj.numWordsOfLength(2);
}
private ArrayList<String> myList;
public WordList(){
myList = new ArrayList<String>();
}
public int numWordsOfLength(int len){
//Code
}
public void removeWordsOfLength(int len){
//Code
}
}
When you call obj.numWordsOfLength(2); you're calling the method numWordsOfLength from ArrayList (which does not exist), not from your WordList class.
First of all, you are adding String to ArrayList, not you're WordList object.
I think what you're trying to achieve will look more like this:
public class WordList {
private List<String> wordList = new ArrayList<>();
public static void main(String[] args) {
WordList wordList = new WordList();
wordList.add("bird");
wordList.add("wizard");
wordList.add("to");
wordList.numWordsOfLength(2);
}
public void add(String word) {
wordList.add(word);
}
public int numWordsOfLength(int len) {
//Code
}
public void removeWordsOfLength(int len) {
//Code
}
}

why there is no element in the list even after populating the list?

package collectionwaliclass;
import java.util.ArrayList;
import java.util.List;
public class ArraylistWaliClass {
public static List<String> list= new ArrayList<>() ;
public static void main(String[] args) {
// TODO Auto-generated method stub
//list= ;
ArraylistWaliClass arraylistWaliClass= new ArraylistWaliClass();
//adding the element to the existing list
int counter=0;
/*while(counter++<10)
{
arraylistWaliClass.addElement("new element"+counter, list);
}*/
//traversing the list in the arryaList
list.forEach((x)->
{
System.out.println(x);
System.out.println("uff");
});
//deleting the list from the arraylist
}
public void addElement(String string, List<String> list)
{
list.add(string);
}
}
because of scope definition, you are just adding elements to the parameter
List<String> list
in
public void addElement(String string, List<String> list)
{
list.add(string);
}
It's working fine if you just un-comment the while loop:
Output:
new element1
new element2
new element3
new element4
new element5
new element6
new element7
new element8
new element9
new element10
Code:
package collectionwaliclass;
import java.util.ArrayList;
import java.util.List;
public class ArraylistWaliClass {
public static List<String> list= new ArrayList<>() ;
public static void main(String[] args) {
// TODO Auto-generated method stub
//list= ;
ArraylistWaliClass arraylistWaliClass= new ArraylistWaliClass();
//adding the element to the existing list
int counter=0;
while(counter++<10)
{
arraylistWaliClass.addElement("new element"+counter, list);
}
//traversing the list in the arryaList
list.forEach((x)->
{
System.out.println(x);
});
//deleting the list from the arraylist
}
public void addElement(String string, List<String> list)
{
list.add(string);
}
}

How to display the content of Java ArrayList?

This is my Data class:
public class Data {
private String name;
private int age;
Data(String n,int a){
name = n;
age = a;
}
public String getName(){
return(name);
}
public void setName(String n){
name = n;
}
public int getAge(){
return(age);
}
public void setAge(int a){
age = a;
}
public void Print(){
System.out.print(("("+GetName()));
System.out.print(",");
System.out.print(GetAge());
System.out.print(") ");
}
}
This is my CS1702_Lab5 class that uses ArrayList and that is supposed to print the content of ArrayList:
import java.util.ArrayList;
public class CS1702_Lab5 {
public static void main(String args[]){
ArrayList<Data> data = new ArrayList<Data>();
data.add(new Data("Fred", 21));
}
private static void PrintDataArray(ArrayList<Data> data) {
for(int i=0;i<data.size();++i){
data.get(i).Print();
}
}
}
I am trying to add new Data which is a StringName and IntAge and then display it but it doesn't seem to work. The console is empty nothing is printed.
Thank you in advance!
You never called your print method from main().
You have to call PrintDataArray() method from main():
import java.util.ArrayList;
public class CS1702_Lab5 {
public static void main(String args[]) {
ArrayList<Data> data = new ArrayList<Data>();
data.add(new Data("Fred", 21));
PrintDataArray(data); // YOU NEED TO ADD THIS LINE.
}
private static void PrintDataArray(ArrayList<Data> data) {
for (int i = 0; i < data.size(); ++i) {
data.get(i).Print();
}
}
}
public static void main(String args[])
{
ArrayList<Data> data = new ArrayList<Data>();
data.add(new Data("Fred", 21));
PrintDataArray(data);
}
you never called PrintDataArray
Call the Print PrintDataArray method in the main method
public static void main(String args[]) {
{
ArrayList<Data> data = new ArrayList<Data>();
data.add(new Data("Fred", 21));
here>PrintDataArray(data);
}
}
You haven't call the method PrintDataArray(data) in your main method...
public static void main(String args[])
{
ArrayList<Data> data = new ArrayList<Data>();
data.add(new Data("Fred", 21));
CS1702_Lab5.PrintDataArray(data);
}
Note: please read naming conventions in Java and try to use them.
Add PrintDataArray() inside your main method
public static void main(String args[])
{
{
ArrayList<Data> data = new ArrayList<Data>();
data.add(new Data("Fred", 21));
PrintDataArray(data);
}
}
private static void PrintDataArray(ArrayList<Data> data)
{
for(int i=0;i<data.size();++i)
{
data.get(i).Print();
}
}
}

Categories