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");
.
Related
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.
I have following lines of code:
private ArrayList<wordClass>[] words;
and
public class wordClass {
public String wordValue = null;
public int val = 0;
public boolean used = false;
}
Is there anyway I can access wordValue, val, and used via words? Like words[5].val? I know I can do that if they are just in an array of wordClass, but I want a dynamic array to make it easier to add and subtract from the array.
And yes, I know the values should be private. Just don't want to write getters and setters yet.
Thanks.
Do you really want an Array of an ArrayList?
It doesn't seem correct.
In Arrays, you use [] to access (words[0]).
In ArrayLists, you should use words.get(0).
The way you have coded, you should use: words[0].get(0).val to get the very first value.
But I recommend you to review your words definition.
ArrayList Documentation: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
Regards,
Bruno
Your code is a bit off for a dynamic array (Java has immutable arrays), so you need an ArrayList. Also, Java uses Capital Letters for class names (please follow the convention) -
// like this, changing wordClass to WordClass. Also, using the diamond operator
private ArrayList<WordClass> words = new ArrayList<>();
To access your WordClass fields you can use something like -
for (WordClass wc : words) {
if (wc.used) {
System.out.println(wc.wordValue + " = " + wc.val);
}
}
Note, you still need to create WordClass instances and place them into the words List.
Write wrapper classes for each value. e.g. What you call "getters".
Then call:
words[1].getWordValue() ==> None
Voila
I am writing a Linked List class that takes in names or numbers, and then prints them out in a list. I managed to write the list normally. Here is what I did:
public String toString(){
return list.toString; //where list is the LinkedList I am calling
}
That works correctly and returns my list after adding 4 elements like this:
[Joe, Jessica, Max, 5]
Now I am trying to convert that same method onto a generic method, so I did 2 things.
Here I created the collections object:
private Collection<E> collection;
public MyLinkedListG(Collection<E> _collection) {
collection= _collection;
}
And here is how I wrote the new toString in collections:
public String toString(){
StringBuilder builder = new StringBuilder();
for(E e : collection) {
builder.append(e); //appends each string
}
return builder.toString();
}
The problem is that now my test class will not allow me to call the LinkedList object I had created before which was:
MyLinkedListG x = new MyLinkedListG();
It states I need to input a collection inside the parameter. How can I call it now? Or am I doing it totally wrong?
If something is not clear please let me know so I can clarify as soon as possible. Thanks in advanced.
From what I can tell, your original class likely did not include a constructor. This means the no-arguments constructor new MyLinkedListG() is provided by default, which is likely what you used to construct an instance of your class.
After your modifications, you added a constructor MyLinkedListG(Collection<E> _collection). Now the no-arguments constructor is not provided by default anymore. If you want to continue to use it, it must be explicitly defined.
Your class will probably have two (or more) constructors in this case, perhaps something like this:
private Collection<E> collection;
public MyLinkedListG(Collection<E> _collection) {
collection= _collection;
}
public MyLinkedListG() {
collection=new LinkedList<E>();
}
Now you can use either constructor for your object.
You can only use an empty constructor if
A) you have not defined a constructor
or
B) if you have explicitly defined an empty constructor.
http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.8.9
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.
Well I wrote some code and all I was doing was for loops, but changing which method I called. I tried using a for loop so it'd be a bit neater (and out of curiosity to see if it could be done), but it doesn't compile when I do it this way, because it doesn't recognize an item in an array as a method, I think. This is what I have:
String[] moveArray = {moveRight,moveDown,moveLeft,moveUp};
for (i = 0; i < 4; i++) {
while (myWumpus.moveArray[i]) {
myWumpus.moveArray[i];
generator.updateDisplay();
}
}
When I try compile I get
not a statement myWumpus.moveArray[i]();
';' expected myWumpus.moveArray[i]();
(It refers to the first statement in the while loop)
So, I think it's maybe because I'm making it an Array of type String? Is there a type Method? Is this at all possible? Any solutions welcome :). Also, I can get it to work using 4 while loops, so you don't need to show me that solution.
You cannot store methods directly in arrays. However you can store objects, which implement the same method differently. For example:
Mover[] moveArray = {new RightMover(), new DownMover() new LeftMover(), new UpMover() };
for (i = 0; i < 4; i++) {
while (myWumpus.moveArray[i]) {
moveArray[i].move();
generator.updateDisplay();
}
}
Yes, you can store methods in arrays using Reflection, however it is likely that what you actually want to do in this situation is use polymorphism.
As an example of polymorphism in relation to your problem - say you created an interface as follows:
public interface MoveCommand {
void move();
}
You can then create implementations as follows:
public class MoveLeftCommand implements MoveCommand {
public void move() {
System.out.println("LEFT");
}
}
etc. for the other move options. You could then store these in an MoveCommand[] or collection like a List<MoveCommand>, and then iterate over the array/collection calling move() on each element, for example:
public class Main {
public static void main(String[] args) {
List<MoveCommand> commands = new ArrayList<MoveCommand>();
commands.add(new MoveLeftCommand());
commands.add(new MoveRightCommand());
commands.add(new MoveLeftCommand());
for (MoveCommand command:commands) {
command.move();
}
}
}
Polymorphism is very powerful, and the above is a very simple example of something called the Command Pattern. Enjoy the rest of your Wumpus World implementation :)
You can't store methods in arrays in Java, because methods aren't first-class objects in Java. It's a reason some people prefer to use other languages like Python, Scheme, etc.
The work-around is to create an interface which contains one method, then create four classes implementing that interface - the MoveRight, MoveLeft, etc... classes. Then you can store instances of those classes in your array and call them all the same way.
You can't call methods like that. But you can using reflection:
Just change the first line in the while-loop to:
Method m = myWumps.getClass().getMethod(moveArray[i]); // if the method is void
m.invoke(myWumps);
(you will have to declare/catch a few exceptions)
But you'd better avoid reflection, and use the Command pattern instead.
Updated answer for Java 8 and onwards-
Since the introduction of lambda expressions and method references in Java 8, storing various methods in variables is now possible. One main issue is that arrays don't currently support generic objects in Java, which makes storing the methods in arrays less doable. However they can be stored in other data structures like a List.
So for some simple examples you can write something like:
List<Comparator<String>> stringComparators = new ArrayList<>();
Comparator<String> comp1 = (s1, s2) -> Integer.compare(s1.length(), s2.length());
stringComparators.add(comp1);
or
List<Consumer<String>> consumers = new ArrayList<>();
Consumer<String> consumer1 = System.out::println;
consumers.add(consumer1);
and then loop/iterate through the List to get the methods.