How to call array out from Java method - java

I created an array Pages in method List.
Could you please advise how to call out one element Pages[1] when accessing method List() from other classes?
public List() {
String[] Pages = {
"www.cnn.com",
"www.bbc.com",
"www.yahoo.com",
};
Many thanks!

You can't call a localvariable from a method directly. You must return it somehow.
Btw, it looks like you don't understand really well how methods work in Java. You should check it.
Here's an example of what do you want to do:
public String[] listPages(){
String [] pages = {"www.cnn.com", "www.bbc.com", "www.yahoo.com"};
return pages;
}
Later if you want to use one of the elements of the array, you should do something like this:
public static void main(String[] args){
String[] res = listPages();
//now we want to print the element one: www.cnn.com
System.out.println(res[0]);
}

You need to create a class named List and a constructor for that class.
Also there are redundant ;, between the elements of the array.

Related

How to append items to ArrayList?

I've got a function to create syllables for words.
I use it like this: syllables(word1field); - creates List with syllables: aa,bb,cc
and syllables(word2field); - creates List with syllables: dd,ee,ff
And in the result I get dd,ee,ff, but I need aa,bb,cc,dd,ee,ff.
Is there possibility to append second list to first?
You get dd,ee,ff because when you call the same method again, it overrides the first ArrayList that is created.
The best thing you could do, that I can think of, is to make your ArrayList global because currently you just keep getting rid of the previous values and create a new ArrayList with the new values you give it. Try doing something like:
public class MyClass {
private List<String> myArray;
public MyClass() {
myArray = new ArrayList<String>();
}
public void syllables(wordfield) {
// do whatever you need to with wordfield
myArray.add(syllable);
}
I don't know how you've got everything laid out but this is the best solution I can think of.

Pass Collection of string to (String... values)

I have a very simple question.
This below method-
newColumnsPredicate
takes input as String... colNames
Below is the method signature as well-
public static SlicePredicate newColumnsPredicate(String... colNames) {
//Some code
}
And I have below collection of strings that I wanted to use in the above method-
final Collection<String> attributeNames
So I decide to use it something like this-
newColumnsPredicate(attributeNames.toString());
This is the right way to do this? As after I run my program, I don't get any data back so I am suspecting it might be possible the way I have added is wrong.
Can anyone help me with this?
String... is a vararg parameter. It is used to indicate that the parameter should either be an array of Strings, or as many String arguments as you like.
Calling toString() on the collection will merely return one string that combines all of the Strings it contains.
You should instead write something that converts your collection to an array, and then pass that in, like:
attributeNames.toArray(new String[attributeNames.size ()])
No, When you do a attributeNames.toString(), you are passing a single String to the method, with a square bracket around them, like "[a, b, c]", Where as your program expects something like "a", "b", "c".
Wouldn't the toArray()function be useful here?
public void test() {
Collection<String> collection = new HashSet<>();
newColumnsPredicate(collection.toArray(new String[collection.size()]));
}
public static SlicePredicate newColumnsPredicate(String... colNames) {
//stuff
}
EDIT:
Whoops, didn't see the other guy answered in the same way.

String[] or ArrayList in Constructor?

I have to make a constructor for an ArrayList. So basically what I want is that this constructor makes an ArrayList.
public Recipe(String[] modifications){
The problem is, it should give something like(example):
String[] modifications = [heatup, cooldown, mix, heatup]
Will the constructor work like this:
Recipe(heatup, cooldown, mix, heatup)
or do I need to change it to somethign like:
Recipe(modifications){
this.myArrayList[1] = modifications[1]
.
.
.
}
thank you and sorry if there are some big mistakes in my code, still learning my Java code.
You can define it this way:
public Recipe(String... modifications)
This will give you a variable argument list, so your constructor will work like this: Recipe(heatup, cooldown, mix).
Inside of the constructor, you can use it just like an array.
change the constructor to varargs:
public Recipe(String ... modifications){
and you can access modifications as String[] however, that's an array, not an ArrayList. If you want an ArrayList, do something like this:
private final List<String> list;
public Recipe(String ... modifications){
this.list = new ArrayList<String>(Arrays.asList(modifications));
}
You could make a constructor with varargs parameters:
public Recipe(String... modifications){...}
then you can call it like this:
Recipe(heatup, cooldown, mix, heatup);
Note though that you should be careful with varargs parameters if you (plan to) have other constructor(s) with potentially conflicting parameter list. However, if this is your only constructor, varargs should be fine.
You could this in your constructor
ArrayList<String> list=new ArrayList<String>();
public Recipe(String[] modifications){
// String a[]={"asas"};
list.addAll(Arrays.asList(modifications));
The second one... of course you can use a for if you just want to copy the elements.
Also you can just copy the array passed by parameter into your class attribute / method variable, unless there is another motive not to do so.
Finally, remember that it would be something like Recipy(String[] modifications) {. You must define the type of the arguments.
And now really finally, myArrayList is a somewhat unfortunate name for an array (there is a class in the API called ArrayList).
What you want is to be able to pass an undetermined number of arguments:
public Recipe(String ... modifications) {
Inside the constructor, modifications is an array.
This will work with this:
new Recipe("heatup", "cooldown", "mix", "heatup");
and with this:
new Recipe();
and with this:
new Recipe("heatup", "mix");
You can use varargs:
public Recipe(String ... modifications) {
// now you can use modifications as an array
for (int f = 0; f < modifications.length; f++) {
System.out.println("#" + f + ": " + modifications[f]);
}
}
.
To use your class you just have to write:
Recipe myRecipe = new Recipe("heatup", "mix");
.

Java - ArrayList<Integer> as Parameter...?

I would like to know how to create a method which takes an ArrayList of Integers (ArrayList) as a parameter and then display the contents of the ArrayList?
I have some code which generates some random numbers and populates the ArrayList with the results, however I keep having errors flag up in eclipse when attempting to create this particular method.
Here is what I have so far:
public void showArray(ArrayList<Integer> array){
return;
}
I know that it is very basic, but I am unsure exactly how to approach it - could it be something like the following?
public void showArray(ArrayList<Integer> array){
Arrays.toString(array);
}
Any assistance would be greatly appreciated.
Thank you.
I'm assuming this is a learning exercise. I'll give you a few hints:
Your method is named showArray, but an ArrayList<T> is of type List<T>, and is not an array. More specifically it is a list that is implemented by internally using an array. Either change the parameter to be an array or else fix the name of the method.
Use an interface if possible instead of passing a concrete class to make your method more reusable.
Minor point: It may be better to have your method return a String, and display the result outside the method.
Try something like this:
public void printList(List<Integer> array) {
String toPrint = ...;
System.out.println(toPrint);
}
You can use a loop and a StringBuilder to construct the toPrint string.
Is there any reason why System.out.println( array ); wouldn't work for you?
Output will be like:
[1, 2, 3]
If you are looking to print the array items, try
public void showArray(ArrayList<Integer> array){
for(int arrayItem : array)
{
System.out.println(arrayItem);
}
}
This sounds like someone wants us to do their homework. You don't have to return anything if you are just displaying it, and if the method has a void return type. I don't know exactly what you want but is it something along the lines of System.out.println(array.elementAt(index))? then you would need a loop.

run a method in an element of an Arraylist in java

I want to know if there's a way to run a method of inside an element of an Arraylist
but I don't want to do it with get because it actually changes fields of the element
thanks
benny.
You don't want to do it with get as in yourList.get(5).someMethod()?
The get method will not "extract" the element it returns, it will only return a copy of the reference. Getting + removing is the implementaiton of remove.
So, unless you have overridden the get method it will not modify the list.
Update and clarification:
List<String> list = new ArrayList<String>();
list.add(myObject); // add a reference to myObject in the list
// (remember, you can't pass around objects in java)
list.get(0).someMethod(); // get a copy of that reference and call someMethod()
Just to make everything even more clear than all the comments did:
public class ReferenceTester {
public static void main(final String[] args) {
final String original = "The One and only one";
final List<String> list = new ArrayList<String>();
list.add(original);
final String copy = list.get(0);
if (original == copy) {
System.out.println("Whoops, these are actually two references to the same object.");
} else {
System.out.println("References to a different objects? A copy?");
}
}
}
Run this class and see what it prints.

Categories