Java ArrayList issue - java

I need some help with a line of code in a program that I am writing. I feel like it's going to be some stupid mistake but I just can't seem to figure out what it is...
ArrayList<Integer> knockSequence; //Default knockSequence
ArrayList<ArrayList<Integer>> customSequences; //used to store custom sequences for client after first connection
ArrayList<ServerClient> connectedClients; //List of connected clients
//...
public void giveNewSequence(ArrayList<Integer> newSequence, ServerClient client) //client MUST be in connectedClients in order for this to work
{
customSequences.get(connectedClients.indexOf(client)) = newSequence;
}
Why won't the line "customSequences.get(......." work? The error I'm getting is saying that it is looking for a variable but a value is being found. Any feedback is appreciated

Why won't the line "customSequences.get(......." work?
You're trying to assign a value to the result of a method call. That's what doesn't work. You can only use the assignment operator with a variable.
I suspect you want:
customSequences.set(connectedClients.indexOf(client), newSequence);
You should also consider using a single collection with a composite type which contains the knock, custom sequence and connected client, rather than managing three separate collections where the values are related by index (which is what I suspect you've got here). You might want to use a map as well, rather than a list.

Related

How do I compare values of an Object with the StreamAPI and Lambda expressions?

I got a problem with streams.
I'm trying to compare everything in my LinkedList to get the latest Medium with the StreamAPI.
The problem I run into is that my methode sucheNeuesMedium() throws NoSuchElementExeption, because get() finds no value. The stream is filled with elements (befor anyone says "be sure that you got objects in your list").
I want to compare them by the value of "Jahr" (it has to be with the StreamAPI and Lambda expressions).
Any ideas how I can make this run? If you need further information I will supply you.
//In class Medienverwaltung
LinkedList<Medium> liste = new LinkedList<Medium>();
Iterator<Medium> it = liste.iterator(); //irrelevant for this task
Stream<Medium> stream = liste.stream();
public Medium sucheNeuesMedium() {
return stream.max(Comparator.comparing(Medium::getJahr)).get();
}
//In abstract class Medium
public int getJahr() {
return jahr;
}
I found my error: I have to operate with liste.stream() and then my comparison.
I always tried it on Imported objects (serialized), meaning the stream stayed empty (the stream got initialized with the empty list).
But if I use liste.stream().max(Comparator.comparing(Medium::getJahr)).get();
it works flawless and multiple times not once. I didn't think about the stream being used aswell. It works, but still thanks for the fast answers.

Execute Java method with parameters from String

I am trying to create a way to give a full method call as a string to a function, which then should try to actually call this method.
This should work with any type and any number and generally arbitrary parameters.
The class where the methods are declared is going to be fixed (probably given as an argument to this classes constructor)
Basically it should work, as if the contents of the String (whatever they might be) would be a line inside the function.
Obviously this function can only try to do this and would need to catch and handle all exceptions (eg. when that method doesn't exist in the given class).
Like this:
public class Thisclass{
String example = "Testmethod(1, 4.23, 'test')";
Class otherclass;
public void Thisclass(Class implementationClass){
this.otherclass = implementationClass;
}
//Calling myFunction like this: myFunction(example);
//Should result in this being called: otherclass.Testmethod(1, 4.23, "test");
public void myFunction(String input){
try{
//Something here
}
catch(Exception ex){
//Handle exceptions
}
}
}
I know how I could do this when I knew the number, type and order of the parameters using reflection, but can I do the same with an unknown number of parameters of unknown type and in an unknown order?
I would be ok with limiting the maximum total number of parameters to something relatively small (eg. 4 or 5), but I would like to leave the type and order of the parameters relatively unlimited.
It would also be ok to limit the types to something like int, float, double, char and String plus arrays of all these.
I know I could overload a method with all sorts of possible parameters, but that is very unpractical, as only allowing a maximum of 4 integers or integer arrays would already bring me up to 8 different versions and allowing a random mix of those two would already need 31 different implementations...
Is this even possible?
Edit:
The comments tell me, that some of you don't really understand what I want to do.
Basically I am parsing a HTML file to be rendered using opengl and I want to be able to make links or buttons in the HTML file execute some method, but I do not want to specify one method, but leave the methods to a different part of the project.
Think:Run Method where MyMethod can be an arbitrary Method. The only thing that is known about the method is that it is implemented in the class otherclass. After parsing the HTML I can get the value of the href attribute as a string, so basically "MyMethod(1, 4.23, 'test')".
For those that suggested that it would be easiest to create / copy a method for every possible combination and order of the data types mentioned above: I did a quick calculation and only accepting 1-4 parameters of the 5 types mentioned above in an arbitrary combination and order, would require over a million different versions of the method. I really doubt that creating all those and somehow not ending with missing or doubled methods at the end is faster than anything else.
The best suggestion so far is the one from saka1029, to basically create an all new java file and compile it using the compiler api and then to run it. I will look into that, as it seems to be the best idea so far.

How to get protected value out of one class and into another

I have two public classes, VAG.java and XY.java. Inside VAG there's a protected value I would very much like, nay, I need to have in XY. All attempts thus far have failed. From inside XY
List<Double> val = VAG.valOfConcern;
yields java.lang.NullPointerException, calling
public List<Double> getVal( ) {
return valOfConcern;
}
on my VAG object yields the same. Now I know what you're thinking; spoof, it's because the object is null, has it been initialized? It has, but maybe that particular variable hasn't been initialized yet? I'm not sure how to ask for help without just posting both full files (~1500 lines) and who's going to want to look through that anyway?
I need a wormhole, is there such a thing? Some hacky way where I can pull off some shared memory type thing in Java? I'm at my wits end, I'm about to start writing the value to a '.txt' and reading it off.
Thank you for listening to me ramble, feel free to tear me a new one, I'm frustrated.

ImplementIon of eval() parser and 2d array in Java

I have really stuck on two Java related issues. One simple and one more difficult.
Regarding the creation of a 2D array, I initialize a table like this:
private String [][] table_of_classifiers = null;
and then, within a function, I fill its contents like this:
String [][] table_of_classifiers = {
{"x1","x","x","x","x"},
{"x2","x","x","x","x"},
{"x3","x","x","x","x"},
{"x4","x","x","x","x"},
{"x5","x","x","x","x"},
{"x6","x","x","x","x"},
};
But as you can guess the second table overwrites (locally) the first one, that is of course not what I want to do. What I do wrong? Note that the dimension of the table is not known from the beginning.
Regarding the creation of a 2D array, I initialize a table like this:
private String [][] table_of_classifiers = null;
Not really. This is the declaration and initialization of a variable that can point to a "2d array", "table" or more exact an "array of arrays" of Strings.
Unless you work with that fact that the variable can/will be null, initializing it to null is usually a bad idea, because you need to do extra work to check for null. Examples:
String[][] a;
// ...
String b = a[0][0];
This won't compile, unless a wasn't initialized in the mean time. This is a good thing, because you can avoid a potential bug.
String[][] a = null;
// ...
String b = a[0][0];
This will however will compile, and if you forgot to actually assign the variable a real array, the program will "crash" with a "null pointer exception" or you need to add additional code/work to check for null.
I fill its contents like this:
String [][] table_of_classifiers = {
{"x1","x","x","x","x"},
{"x2","x","x","x","x"},
{"x3","x","x","x","x"},
{"x4","x","x","x","x"},
{"x5","x","x","x","x"},
{"x6","x","x","x","x"},
};
You are not "filling" anything here. For something to be filled it must exist first, but you haven't created anything yet.
Here you are declaring a second variable of the same name, which is only possible if you are in a different scope that the first one, and in that case you are "hiding" ("shadowing") the original variable if it originally was accessible from this new scope.
But as you can guess the second table overwrites (locally) the first
one, that is of course not what I want to do. What I do wrong?
Which "first" table? There was no first table until now, only a first variable. The others have shown you what you need to do to assign the "table" to the original variable, by not using the "declaration" String[][] at the beginning of the line.
Otherwise it's impossible to say what you are "doing wrong" because you haven't really explained what you are attempting to do.
Note that the dimension of the table is not known from the beginning.
It's not? How/why are you using a array literal then? Literal arrays are for creating arrays of a fixed size with a fixed "prefilling".
What exactly do mean with "the beginning"? Isn't the size known when you are programming (during compile time) or when the program starts (at run time)?
If you get the size of the array during run time you can create a normal array with new:
int a = ...;
int b = ...; // Get the sizes from somewhere, e.g, user input
String[][] table_of_classifiers = new String[a][b];
// Now you have an "empty" table
If size "changes" during run time, then - depending on what you are actually attempting to do - then an array is the wrong tool and you should be using a List implementation such as ArrayList instead.
Regarding "eval", as the others say, Java is a compiled language making "eval" basically impossible. The is "reflection" or the use of Class types to achieve what you are hinting at, but you really need to explain much more extensively what you are trying to achieve, then it may be possible to help you here.
However reflection and CLass types are a complicated matter, and considering you are obviously struggling with the most basic Java concepts, you have a long way to go to until you will be able to do what you want to do.
Just do:
class Foo {
private String [][] table_of_classifiers = null;
void bar() {
table_of_classifiers = new String[][] {
{"x1","x","x","x","x"},
{"x2","x","x","x","x"},
{"x3","x","x","x","x"},
{"x4","x","x","x","x"},
{"x5","x","x","x","x"},
{"x6","x","x","x","x"},
};
}
}
Java doesn't have eval (because it's a compiled language), but it does have reflection. It's almost certainly not the best approach to whatever it is that you want to do, though.
Regarding your first problem: to assign to table_of_classifiers without redeclaring it, write:
table_of_classifiers = new String[][] {
{"x1","x","x","x","x"},
{"x2","x","x","x","x"},
{"x3","x","x","x","x"},
{"x4","x","x","x","x"},
{"x5","x","x","x","x"},
{"x6","x","x","x","x"},
};
Regarding eval . . . the problem is that the run-time doesn't have the names of scoped local variables, and although it can get the names of instance variables, it has to do that within the context of an object. It's possible to address these sorts of issues, but it's non-trivial, and will involve major compromises. I think you have to thoroughly understand how scoping works and how reflection works before you start figuring out what features eval will support, because otherwise you'll just be disappointed at all the requirements you give it that turn out to be impossible.

Saving List of Strings in Java

am having problem in Saving some data in my Java code.
I have like three different methods which do some respective tasks. Am calling these methods using Hessian from Php client. And am not calling this three methods at a time. Each method will create some arrays(contains strings, int, float), and some time i have to use those arrays which was created my previous methods call in this present method.
Is there any way i can save that Arrays(not in database), may be a List or Array which will not flush the memory unless i say soo..
Example
public class top{
Method1(){
String[] stringA = {some string data} ;
}
Method2(){
for(string data : stringA){
I use array of stringA from method1 without calling the whole method1. I need that string value to be save untill i flush it out.
}
}
}
This is not a complete code.. not even a code. Am just trying to explain the issue.
Any help please.
Thanks.
How about defining the stringA as a instance variable instead of a local variable ?
You could set up stringA as a local variable to your class.
public class SomeClass {
private String[] stringA;
public void method1(){
stingA = "something";
}
public void method2(){
for(string data : stringA){
I use array of stringA from method1 which out calling the whole method. I need that string value to be save untill i flush it out.
}
}
You could also use a ArrayList, instead of an array for your string. This will allow you to dynamically grow your list. If you want to "flush" it, you could just call the clear() method
ArrayList<String> myArr = new ArrayList<String>();
myArr.add("string1");
myArr.add("string2");
//clear the ArrayList
myArr.clear()
If you want to remember values between method calls, it should be a instance (class
level) variable. If yours is a web application, you can use session variables.
[Your code is not complete, actually its not even there. Posting complete code helps someone trying to answer to understand the problem correctly.]
I don't know anything about hessian, but it looks like that the component that handles the call is stateless.
I agree with Nivas' answer in this case.
However, should you need extra functionality (search, etc) with the storage and have some hardware resource to spend you can also use something like HSQLDB which have in-memory DB storage (very fast).

Categories