How to access same method with different objects in java - java

I have created an two Arraylist and a Method for printing the elements of array list. How can I use the same method to print the elements of both ArrayList ?

Simply pass the object of the created ArrayList to the function as paramter.
Here's a short example for printing the ArrayList:
Assuming you put the code inside a class, leaving a snippet here.
I'll demonstrate it with Integer examples.
static void printArrayList(ArrayList<Integer> a){
for(Integer i:a)
System.out.print(i+" ");
System.out.println("");
}
//in the main function:
public static void main(String[] args){
// input driver code
ArrayList<Integer> a1 = new ArrayList<>();
ArrayList<Integer> a2 = new ArrayList<>();
a1.add(1);
a2.add(10);
printArrayList(a1);
printArrayList(a2);
}
For more information on passing parameters - visit official documentation: Function Parameters
For more information on ArrayList - visit official documentation:
ArrayList

you can do it:
public static void printBothListArgs(List<AnyType> listOne, List<AnyType> listTwo){
Stream.concat(listOne.stream(), listTwo.stream()).forEach(System.out::println);
}

Related

printing all subsequences of an array using recursion in JAVA

The following code for above requirement. However I am not getting proper output. There is problem with input list that I am passing in recursion
import java.util.ArrayList;
import java.util.Collections;
public class abc
{
public static void m(ArrayList<Integer> op, ArrayList<Integer> ip) {
if(ip.size()==0) {
System.out.println(op);
return;
}
ArrayList<Integer> l1=new ArrayList<Integer>();
ArrayList<Integer> l2=new ArrayList<Integer>();
l1.addAll(op);
l2.addAll(op);
l1.add(ip.get(0));
ip.remove(0);
m(l2,ip);
m(l1,ip);
}
public static void main(String[] args) {
Integer [] z = {1,3,2};
ArrayList<Integer> ip=new ArrayList<Integer>();
Collections.addAll(ip, z);
ArrayList<Integer> op=new ArrayList<Integer>();
m(op,ip);
}
}
The problem is not, like you said in your comment, that the list ip keeps elements of the previous function call. The problem is that you don't create a new arraylist as ip parameter for the next function call, meaning, as it is call by reference, that you remove the elements of one function call already in the other function call. You can fix this by just creating a new array list for the new function call, like you already to for op. However you could also use this:
m(l2,new ArrayList<>(ip));
m(l1,new ArrayList<>(ip));
so you don't have to use an extra addAll() ;)

Collection.sort(arraylist) in a function sorting another arraylist

say, I made an arraylist in (public class class1(String args[]))
static List<Double> list1 = new ArrayList<Double>();
then I pass this arraylist to a function in (public static void main(String args[]))
biggestvalue(list1);
this is the function for example:
public static double biggestvalue(List<Double> list){
Collections.sort(list);
return list.get(list.size()-1);
}
I pass it into a function so that hopefully it will only sort list but not list1, but then list1 gets sorted as well, and I do not understand why that is.
Therefore, please explain to me why that is, and what solutions to this error are out there?
You only pass a reference to the List when you pass it as an argument. Therefore, both list and list1 point to the same List.
A good rule of thumb is to not modify objects passed into a method, so I would make a copy inside the method:
public static double biggestvalue(List<Double> list){
List<Double> temp = new ArrayList<>(list);
Collections.sort(temp);
return temp.get(temp.size()-1);
}
list1 gets sorted as well because you are passing a reference to that object. You want to duplicate the list before sorting it, so the original object doesn't get modified:
List<Double> dup = new ArrayList<>(list);
Collections.sort(dup);
return dup.get(dup.size() - 1);

how to store a array of String in Array List. can we use array of an Array List. if yes then how?

is it possible to run the following code with logic in 6th line ?
public class arraylist{
public static void main(String args{}){
String s[]={"Sam","Tom","Jerry"};
ArrayList al=new ArrayList();
al.add(s);//i want this type of logic so i can add the elements of string once.is it possible?
}
Iterator it=al1.iterator();
while(it.hasNext())
{
String element=String.valueOf(it.next());
System.out.print("Element"+element);
}
}
Change al.add(s); by al.addAll(Arrays.asList(s)); and you should be all set.
Try the following:
ArrayList<String> al = new ArrayList<String>(Arrays.asList(s));
You have the answer in your question.
When you say you want to convert array asList
As many have already suggested, use Arrays.asList. But before the code would work, you would still need to fix the formatting as you have code outside the main method that is referring to your array list variable in the main method.
public static void main(String[] args){
String s[]={"Sam","Tom","Jerry"};
ArrayList al=new ArrayList();
al.add(Arrays.asList(s));
Iterator it=al.iterator();
while(it.hasNext())
{
String element=String.valueOf(it.next());
System.out.print("Element"+element);
}
}
al.add(s);//i want this type of logic so i can add the elements of string once.is it possible ?
Yes. It is possible.You can add any object to ArrayList including array object.
But while iterating the ArrayList object you will get an array element by calling it.next().So output will be String representation of array object not the array elements
So try this
String s[]={"Sam","Tom","Jerry"};
ArrayList<String> al=Arrays.asList(s);
Iterator it=al.iterator();
while(it.hasNext())
{
String element=String.valueOf(it.next());
System.out.print("Element"+element);
}
I did the following to store arrays in a ArrayList. The declaration is:
ArrayList<String[]> training = new ArrayList<String[]>();
To input the words and add it:
String input = sc.nextLine();
s1 = input.split(" ");
training.add(s1);
The split method splits the string with spaces and stores each word in the respective index in array s1 which was already declared with the size required for the program."sc" is the scanner object already declared.The individual arrays can be accessed by using:
String s4[] = training.get(index_of_array_you_want);
Element[] array = {new Element(1), new Element(2), new Element(3)};
ArrayList arr=new ArrayList(Arrays.asList(array))

Implementing a new LinkedList method in Java

I have an assignment that involves creating three methods that manipulate a linked list. The instructions dictate that I use the following constructor:
public MyList (LinkedList<Integer> list) {
...
}
However, Eclipse seems to not like my code regardless of how I try integrate it. Here's my current attempt:
import java.util.*;
public class ListClass {
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<Integer>();
list.add(10);
list = MyList(list);
}
public MyList (LinkedList<Integer> list){
LinkedList<Integer> r = list;
return r;
}
}
Now I thought that the MyList constructor above would happily just return the list entered, but my Java skills are really weak. I've been going through the tutorials and gave this a go, but it hasn't worked as I thought it would.
Anyway so Eclipse is giving me two errors - at the "list = MyLIst(list);" line it says the method MyList is undefined for ListClass, and at the "public MyList" line it says "the return type for the method is missing" - but I've told it that r is a linked list, and to return that.
This hurts my brain and I can't manage to figure it out, can anyone give me a hand? I think if I were able to get the above code working, I should be able to get the rest sorted.
Newer code
As rightfully pointed out, my class name isn't the same as my supposed constructor name. So here's the adjusted code:
import java.util.LinkedList;
public class MyList {
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<Integer>();
list.add(10);
list.add(-20);
MyList(list);
}
public MyList(LinkedList<Integer> list) {
LinkedList<Integer> newList = list;
System.out.println(newList);
}
}
This has solved the "return type" error (thank you), though I'm still getting the "undefined" error.
What's missing in the declaration of your method MyList is the return type of the method:
public MyList (LinkedList<Integer> list)
should be something like
public LinkedList<Integer> MyList (LinkedList<Integer> list)
Besides that, the usual convention for method names is camel case, but starting with a lower-case letter. I'd call it myList instead of MyList (you should choose a better name for the method that reflects what the purpose of the method is).
If
public MyList (LinkedList<Integer> list) {
...
}
is supposed to be a Constructor, the class also must be named MyList. You can't return anything from a constructor, so just leave the declaration of it as it is.
Just rename your class, save the LinkedList to a private field in the constructor above, and then add the methods you are supposed to implement to the MyList class.
To get rid of the undefined problem, you need to create your list using 'new':
MyList myList = new MyList(list);
With your modified code, there's still a few things to correct:
In Java, you call a constructor in order to create a new Object. You probably want to keep this object when you create it as part of your main() method, using something like the following in order to prevent your 'undefined' error:
MyList ml = new MyList(list);
As part of your Constructor you only store the LinkedList<Integer> that's passed in as as local variable, and not as a class variable. Correct this with the following declaration at the top of your class:
public class MyList {
private LinkedList<Integer> list;
//...
Structure for additional functionality
In order to add the additional functionality as described in your comment below, I'd use the following sort of structure (Obviously you still need to implement the methods, but you can see where I'd put them):
import java.util.LinkedList;
public class MyList {
private LinkedList<Integer> list;
public MyList(LinkedList<Integer> list) {
this.list = list;
}
public LinkedList<Integer> reverse() {
//Create a reversed list
return rList;
}
public LinkedList<Integer> odd() {
//Create a list of the odd elements
return oddList
}
public LinkedList<Integer> even() {
//Create a list of the even elements
return evenList;
}
#Override
public String toString() {
return list.toString();
}
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<Integer>();
list.add(0);
list.add(2);
list.add(4);
MyList ml = new MyList(list);
System.out.println("MyList: " + ml);
LinkedList<Integer> tsil = ml.reverse();
System.out.println("Reversed: " + tsil);
LinkedList<Integer> ls = ml.odd();
System.out.println("Odd: " + ls);
LinkedList<Integer> it = ml.even();
System.out.println("Even: " + it);
}
}
The problem here is that a constructor must have the same name of its enclosing class. However, you're trying to name a MyList constructor inside a class named ListClass.
So, either name both your class and the constructor MyList or name them ListClass.
As for the "undefined" issue, you can't directly call a constructor. You have to use it in a "new" statement, as it is used to create new instances of the class:
MyList someList = new MyList(); // variable someList will hold a new MyList instance
or
new MyList(); // instance without a reference variable.

Java - Reading from an ArrayList from another class

We've not covered ArrayLists only Arrays and 2D arrays. What I need to do is be able to read from an ArrayList from another class. The main aim is to read from them in a for loop and use the values stored in them to display items. However, I have made this quick program to test it out and keep getting this error
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:604)
at java.util.ArrayList.get(ArrayList.java:382)
at Main.Main(Main.java:14)
Here is my code
import java.util.ArrayList;
public class Main
{
public static void Main()
{
System.out.println("Test");
ArrayList <Objects> xcoords = new ArrayList<Objects>();
for( int x = 1 ; x < xcoords.size() ; x++ )
{
System.out.println(xcoords.get(x));
}
}
}
And then the class where the ArrayList is
import java.util.ArrayList;
public class Objects
{
public void xco()
{
ArrayList xcoords = new ArrayList();
//X coords
//Destroyable
xcoords.add(5);
xcoords.add(25);
xcoords.add(5);
xcoords.add(5);
xcoords.add(25);
xcoords.add(5);
//Static Walls
xcoords.add(600);
xcoords.add(400);
xcoords.add(600);
}
}
If someone can point me in the correct direction it would be so valuable. I've tried to debug however I can get anything helpful.
Thanks in advance.
Strictly speaking, the exception is due to indexing location 1 of an ArrayList with 0 elements. Notice where you start you for loop index variable x. But consider this line:
ArrayList <Objects> xcoords = new ArrayList<Objects>();
xcoords points to a new, empty ArrayList, not the one you created in class Objects. To get that ArrayList, change the method xco like
public ArrayList<Integer> xco() { // make sure to parameterize the ArrayList
ArrayList<Integer> xcoords = new ArrayList<Integer>();
// .. add all the elements ..
return xcoords;
}
then, in your main method
public static void main(String [] args) { // add correct arguments
//..
ArrayList <Integer> xcoords = (new Objects()).xco();
for( int x = 0 ; x < xcoords.size() ; x++ ) { // start from index 0
System.out.println(xcoords.get(x));
}
}
Here you're simply creating two completely unrelated lists. Either have the array list be a property of the Objects class and retrieve it through an instance method, or return it from an instance or static method, or make the property static. IMO the first two are preferable in most situations.
public class Objects {
public static List<Integer> getXcoords() {
List<Integer> xcoords = new ArrayList<Integer>();
// Your same code, but adding:
return xoords;
}
}
Then to use it:
import java.util.ArrayList;
public class Main {
// Note the lower-case "main" here. You want that.
public static void main() {
List<Integer> xcoords = Objects.getXcoords();
// etc.
Also, your List should be of Integer, not of Objects, which would create a collection holding instances of Objects. You may want to take a step back and relate lists to arrays in a better way--you wouldn't create an array of Objects, would you? No, you'd have an array of int or Integer.
Also, there's Arrays.asList.
You have an IndexOutOfBoundsException which means that you are trying to access an element in an array which is not existing.
But in your code posted here you are not accessing an array at all (your for loop will not execute once because the list is empty), which means that your exception is thrown somewhere else.
But also your code doesn't make any sense. I refactored it for you while staying as close to your code as possible, so you can see how it could work:
public static void main(String[] args){
Objects myObjects = new Objects();
ArrayList<Integer> listFromMyObjects = myObjects.getList();
for( int x = 0 ; x < listFromMyObjects.size() ; x++ )
{
System.out.println(listFromMyObjects.get(x));
}
}
public class Objects
{
private ArrayList<Integer> myList;
public Objects(){
myList = new ArrayList<Integer>();
myList.add(5);
myList.add(25);
myList.add(5);
myList.add(5);
myList.add(25);
myList.add(5);
myList.add(600);
myList.add(400);
myList.add(600);
}
public ArrayList<Integer> getList(){
return myList;
}
}

Categories

Resources