how can we compare two list? [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I have 2 lists of classes namely StuPersonal of Database1,StuPersonal of Database2 of different size.
public List<StuPersonal> stpers(){
int size=0;
Session s=getmSession();
Transaction tx=s.beginTransaction();
List<StuPersonal> splM=new ArrayList();
Query q=s.createQuery("from StuPersonal");
splM=q.list();
tx.commit();
s.close();
return splM;
}
public List<StuPersonal> stpersl(){
int size=0;
List<StuPersonal> splL=new ArrayList();
Session s=getlSession();
Transaction tx=s.beginTransaction();
List<StuPersonal> spl=new ArrayList();
Query q=s.createQuery("from StuPersonal");
splL=q.list();
tx.commit();
s.close();
return splL;
}
Now i have to compare both the lists and need to take the items which are not in the presented in the second list.i.e some objects are not in the class 2 list so it needs to be stored. I have written this code which is not working properly. Please advice.
for(StuPersonal cl:sp)
{
for(StuPersonal cl2:sp2)
{
if(cl.getid().equals(cl2.getid()))
{
//i++;
break;
}
else
{
fun.updatelist(cl.getid());
break;
}
}
}

You are Checking the ID of List object not the Class_1 Object Id
if(cl.getid() == cl2.getid())
{
//i++;
break;
} else
{
fun.updatelist(cl2.getid());
break;
}
And you are using equals method, considering id as long not String.

You're not helping yourself by choosing awful names for your variables and methods, not respecting the standard naming conventions, and not correctly indenting your code.
Anyway, you should try to write short methods that do one thing only, and that represent the steps in your task. Your task is to produce a list of objects that are present in list1 but are not in present in list 2. And "being present" here means "an object with the same ID exists in the list".
So start by writing a method isPresent():
/**
* Returns true if an object with the same ID as the ID of the given object is
* present in the given list
*/
private boolean isPresent(StuPersonal object, List<StuPersonal> list) {
for (StuPersonal candidate : list) {
if (candidate.getId().equals(object.getId()) {
return true;
}
}
return false;
}
Now you can use this method in your algorithm:
// start with an empty list
List<StuPersonal result = new ArrayList<>();
// add every element of list1 unless it's present in list2
for (StuPersonal s : list1) {
if (!isPresent(s, list2)) {
result.add(s);
}
}

Here is an example with String for your scenario.
List<String> firstList = Arrays.asList("obj1", "obj2", "obj3");
List<String> secondList = Arrays.asList("obj1", "obj2", "obj3", "obj4", "obj5");
List<String> storedList = new ArrayList<String>();
for (String obj2 : secondList) {
if (!firstList.contains(obj2)) {
storedList.add(obj2);
}
}

Related

Instantiating an object in array list [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
An example of a method that uses a normal array object.
public static void free Customer(customer[] customers, supplement[] supplements)
{
for(int i=0;i<customers.length;i++)
{
customers[i]=new customer();
customers[i].read Input();
for(int s=0;s<supplements.length;s++)
{
supplements[i]=new supplement();
supplements[i].read Input();
}
}
}
My question is, how do i convert this --> customers[i]=new customer();
and this --> customers[i].read Input(); into a valid Array list code?
I tried putting customers[i]=new customer(); & customers[i].read Input();
into the method below but the compiler returns an error saying that
"Array List required but array found"
This is a skeleton of the free Customer method that is using Array list.
public static void free Customer(Array List<customer> customers,
Array List<supplement>supplements)
{
for(int i=0;i<customers.size();i++)
{
}
}
Do it as follows:
public static void freeCustomer(ArrayList<customer> customers, ArrayList<supplement>supplements) {
for(int i=0;i<customers.size();i++) {
customers.set(i, new customer());
customers.get(i).readInput();
}
}

I need to construct a family tree based on the specifications given below. want it to be in Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
The input will be as
Name of parent number of children names of children separated by space
END
Number of lines in next input
Ancestor child
Eg:
heena 2 kishan kinjal
Kishan 1 ansh
END
1
Kinjal ansh
Here as shown in example we can take multiple line Input and input is terminated by END. After that we give a number which specifies how many lines are there in next input.
The next input asks whether kinjal is ancestor of ansh or not.
The output should be NO.
Can anyone help?
I have created 2 separate list containing number and names. I am totally lost please help.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
class test3
{
//static int index;
public static void main(String[] args)
{
List<String> temp=new ArrayList<>();
ArrayList<String> words=new ArrayList<>();
ArrayList<Integer> number=new ArrayList<>();
String t="";
String t1="END";
String rootfromlist="";
Scanner scan=new Scanner(System.in);
while (scan.hasNext())
{
t=scan.next();
if(t.equals(t1)) {
break;
} else {
temp.add(t);
}
}
String[] temp2=new String[temp.size()];
for(int i=0;i<temp2.length;i++)
{
temp2[i]=temp.get(i);
}
Iterator<String> itr=temp.iterator();
String regex="[0-9]+";
int i=0,j=0;
while(itr.hasNext())
{
temp2[i]=(String)itr.next();
if(temp2[i].matches(regex))
{
number.add(Integer.parseInt(temp2[i]));
i--;
j++;
}
else
{
words.add(temp2[i]);
}
i++;
}
Iterator itr2=number.iterator();
while(itr2.hasNext())
{
System.out.println(itr2.next());
}
System.out.println(number.get(0));
List<String> wodupli=words.stream().distinct().collect(Collectors.toList());
ArrayList<String> a=new ArrayList<>();
boolean prev=false;
int index=0;
String tt="null";
//here i am trying to make list "a" such that as array of binary tree. that is then i will able to access children of node by formula 2*i+1 and 2*i+2. but the logic id not correct
for(int k=0;k<number.size();k++)
{
if(number.get(k)==2)
{
if(prev==false)
{
a.add(wodupli.get(index));
a.add(wodupli.get(2*index+1));
a.add(wodupli.get(2*index+2));
}
if(prev==true)
{
a.add(wodupli.get(index-1));
a.add(wodupli.get(2*index));
a.add(wodupli.get(2*index+1));
}
index=index+3;
prev=false;
}
if(number.get(k)==1)
{
a.add(wodupli.get(index));
a.add(wodupli.get(index+1));
a.add(tt);
index+=3;
prev=true;
}
}
for(int l=0;l<a.size();l++)
{
System.out.println(a.get(l));
}
}
}
i want to know how to create a tree dynamically. because here binary tree logic wont work.
OK, so your problem seems to be that you don't know what data structure to use.
As you have figured out, an binary search tree is not what you need:
A binary search tree is for looking up things using a key. The tree represents the relationships between keys and values. You want to represent the relationships between values; i.e. people in a family tree.
A family tree is not binary. One person can have more than two children.
So what you actually need to do is to design a class that represents a person: lets call it Person. A Person will need to represent at least the following things about the person:
the person's name
the person's children ... which could be a list or an array
Secondly, you will need some kind of map data structure that maps a person's name to their Person object. You can use a Map<String, Person> for this.
Next you need some code that will read your input file, and create the Person records and populate the map. The code should also be linking up the Person records into the family tree(s).
Finally, you will need some simple code that will answer the question "is A an ancestor of B". Hint: that is the same question as "is B a descendant of A" ... which can be answered by recursively walking the tree for "A".
The bad news is that most of the code you have written probably needs to be thrown away. The good news is that the new code will be a lot more logical / easier to understand.

Array does not show up when called? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
In my code I created a class called Inventory to store my information in an array. I created a method to add strings, and a method to display all the information stored in the array. Something went wrong along the way for my code will execute, but it will not show any of the information that I stored in the array, just a blank command window. Here is the man class.
public class Game {
public static void main(String[] args) {
Inventory playersInventory = new Inventory();
playersInventory.addInventory("Knife");
playersInventory.addInventory("Food");
playersInventory.addInventory("Water");
playersInventory.displayInventory();
}
}
and here is the Inventory class
public class Inventory {
private String[] inventoryItem = new String[10];
public void addInventory(String item){
int x = 0;
while (true) {
if (inventoryItem[x]== null){
item = inventoryItem[x];
break;
}
else {
x++;
}
}
}
public void displayInventory(){
int x = 0;
while (true){
if (inventoryItem[x] == null){
break;
}
else{
System.out.println(inventoryItem[x] + "\n");
x++;
}
}
}
}
The problem lies in this line:
item = inventoryItem[x];
The = evaluate the expression on the right and assigns the result to the variable on the left. So what you're doing there is assigning inventoryItem[x] to item.
In other words, you are not mutating the array, but assigning a new value to the parameter, which does practically nothing.
I guess you want to add the parameter into the array. So your assignment statement should be the other way around:
inventoryItem[x] = item;
Actually, to avoid confusion, just use an ArrayList!
public class Inventory {
private ArrayList<String> inventoryItem = new ArrayList<>();
public void addInventory(String item){
inventoryItem.add(item);
}
public void displayInventory(){
for (Sting item: inventoryItem) {
if (item != null) {
System.out.println(item + "\n");
}
}
}
}
Isn't that much cleaner?
Your line of code
item = inventoryItem[x];
should be
inventoryItem[x] = item;
You are assigning inventoryItem[x]; to item where as you need the reverse.
Assign value inventoryItem[x] = item;
You did not put the item in the array "inventoryItem", Hence no information was displayed.
Change your code to following to populate the array
if (inventoryItem[x]== null){
inventoryItem[x]=item ;
break;
}

JAVA. Searching a value and displays the data [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
'm currently making a purchase program. I'm almost halfway done on it, the only thing i need is. when i Press 1 for purchase it will give me an option to input the Item Code that i stored in my inventory. And then it respectively displays the datas or values corresponds on my inputted code based on my stored products on my inventory.
PS: im new in java and i know my codes are still basic cus im still learning java on my own. And my variables are not yet changed into Arraylist cus i just found out that Arraylist is much better than a plain Array in storing collection of data.
Any suggestions is highly appreciated and welcome. Would stick on using Arraylist or Array. not Hashset or etc.. Thank you Guys!
Hope you guys could help me. Thanks!
class Item {
public final int sku;
public final String desc;
public final type other_fields;
public Item(int s, String d, type fields...) {
// set fields
}
}
or if you really want to be clever
abstract class Item {
public final int sku
// ....
}
class PinkCurtains extends Item {
public PinkCurtains() {
sku = 129534;
desc = "Adorable Pink Indoor Curtains";
}
}
class FuzzyTowel extends Item {
public FuzzyTowel() {
sku = 874164;
desc = "Machine Washable Fuzzy Towel";
}
}
then populate your list and search away
ArrayList<Item> catalog = new ArrayList<Item>(0);
for (int i = 0; i < numItems; i++) {
catalog.add(new Item(arg, arg, arg...));
}
// or
catalog.add(new PinkCurtains());
catalog.add(new FuzzyTowel());
for (Item item : catalog) {
if (chosenItem == item.sku) {
// do all your stuff
}
}
They are called Iterables for a reason. You don't have to make classes if you don't want to. ArrayList also has searching methods, contains() and indexOf() for example:
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
If you want to fill in the fields as you go you can make a class that lets you do that:
class Item {
public int id;
public float price;
}
ArrayList<Item> cart = new ArrayList<Item>(0);
do {
Item item = new Item();
item.id = userInput;
item.price = userInput;
cart.add(item);
} while (userInputting);
float total = 0;
for (Item i : cart) {
total += i.price;
}
// using a regular for loop instead of for-each
for (int i = 0; i < cart.size(); i++) {
Item item = cart.get(i);
// or search for something particular
if (item.id == searchID) {
System.out.println("found item " + item.id + " with price $" + item.price);
}
// equivalent to
if (ids[i] == searchID) {
System.out.println("found item " + ids[i] + " with price $" + prices[i]);
}
}
Each time the user wants to add an item, you just make a new one, fill in the fields and add it to the list.

Access the value from list in java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
This is one of my class
class number11 {
String ab;
int i;
public number11(String ab,int i) {
this.ab=ab;
this.i=i;
}
}
And in main method, I used
List<number11> n1= new ArrayList<number11>();
How can I access the value of integers and String contained in List? I do wish just to print them but to use further.
{Closed ,Thank you all}
Just loop over the list:
for (number11 n : list) {
String ab = n.ab;
int i = n.i;
//print ab and i
}
Note that number11 should be in CamelCase to follow Java's conventions: Number11.
From your question it seems you want list of your objects,
Before continuing, please create getters and setters, I've used them
Also your class name should be camelCase. Number11 is valid but not number11
You can fill the list using
List<number11> list = new ArrayList<number11>();
list.add(new number11("a",1));
list.add(new number11("b",2));
To access the members,
for (number11 n : list) {
String ab = n.getAb();
int i = n.getI();
}
like this
List<number11> n1= new ArrayList<number11>();
for(number11 n:n1){
System.out.println("String value: "+n.ab);
System.out.println("int value: "+n.i);
}
According to better coding standards.Follow the below rules
1.Change you class so that It starts with a camel case.
2.Change variables to private.
3.Add setter and getter methods
Assuming you have added values to the ArrayList you can read values by using code such as n1.get(0).ab or n1.get(0).i.
List l = new ArrayList<number11>();
l.add(new number11("x",1));
l.add(new number11("y",2));
for (number11 element : l) {
System.out.println(element.ab + " "+ element.i);
}
You might first want to add getter methods to your class number11.
e.g
public class number11{
String ab;
int i;
public number11(String ab,int i)
{
this.ab=ab;
this.i=i;
}
public int getI(){
return i;
}
public String getAb(){
return ab;
}
}
You need to obtain a reference to the particular object held inside the ArrayList via the get(index) method where index is the element number starting with 0. Simply call the getter methods to retrieve the values.
e.g
List<number11> n1= new ArrayList<number11>();
//Adding the object
n1.add(new number11("Test", 4));
//Retrieving the object.
number11 inst = n1.get(0);
//Retrieve and print the values
System.out.println(inst.getAb());
System.out.println(inst.getI());
For better convention change your class structure to,
class Number11 {
private String ab;
private int i;
public Number11(String ab,int i) {
this.ab=ab;
this.i=i;
}
public String getAb() {
return ab;
}
public void setAb(String ab) {
this.ab = ab;
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
}
Access in this way.
List<number11> n1= new ArrayList<number11>();
if(n1!=null && n1.size()>0){
for (Number11 n : n1) {
String ab = n.getAb();
int i = n.getI();
//print ab and i
}
}
List<number11> n1= new ArrayList<number11>();
after adding values to this list n1 it will contains number11 type objects from index 0 to n-1, where n is number of element you added to list.
Then you can call what ever object as follows
n1.get(1) // this will return 2nd object in the list
It will contain ab and i
You can call them as follows
n1.get(1).getab // 2nd element ab value in list n1
n1.get(1).i // 2nd element i value in list n1
List Interface allows to:
Positional access — manipulates elements based on their numerical position in the list
MyClass obj = myList.get(24); //--get 25th item of a List<MyClass>--
Iteration access — extends Iterator semantics to take advantage of the list's sequential nature
for(MyClass obj : myList){ //-- go through all items of a List<MyClass> one by one--
int i = obj.someField;
}
Once you have your object, you can access its fields.

Categories