i'm working on a project that i have to use HashMaps on.
I'm fairly new to java, so am i right in thinking that you have to include this in each class that I want to use HashMaps on, or should this be included in each class anyway?
public static void main(String args[])
This is the whole class. Ive tried it without the main method but I just get errors.
import java.util.HashMap;
public class Product
{
public static void main(String args[]) {
HashMap<String, int> product = new HashMap<String, int>();
product.put("product1", 1);
product.put("product2", 2);
}
}
If i dont have the main method in it comes up with an error on the line...
product.put("prodcut1", 1);
It's not that your code has to be in the main method, but it has to be in some method, or an initializer block. If you put your code in a non-main method, it will still work fine.
You only need main in the driver of your program not in every single class. After having written your code/classes that require HashMaps you can then put them inside
public static void main(String args[])
Also since you mentioned HashMaps are not working, have you imported them in the other classes where you are trying to use them like so?
import java.util.HashMap
Short answer: no. A main method serves as the main starting point for an entire program. It has no bearing on what classes can be used in the program.
If you want to use a HashMap...
Include the package that houses the HashMap class
Declare variables of the type HashMap
Either as instance fields of a class or as local variables in a method/function
Use the variables you declared
If you are looking for a way to declare the HashMap at the time of declaration and you dont want the initialization to be in a method or block, you can use the following:
HashMap<String, int> product = new HashMap<String, int>(){{
put("product1", 1);
put("product2", 2);
}};
Related
This question already has answers here:
What is a class literal in Java?
(10 answers)
Closed 5 years ago.
To illustrate the contrast. Look at the following java snippet:
public class Janerio {
public static void main(String[] args) {
new Janerio().enemy();
}
public static void enemy() {
System.out.println("Launch an attack");
}
}
The above code works very fine and seems to be yes as answer to this question as the output turns to be as follows.
Launch an attack
But at the very next moment when I run the following snippet
public class Janerio {
public static void main(String[] args) {
System.out.println(new Janerio().class);
}
}
I get the compile time error
/Janerio.java:3: error: <identifier> expected
System.out.println(new Janerio().class);}
^
/Janerio.java:3: error: ';' expected
System.out.println(new Janerio().class);}
^
2 errors
I don't see why such a situation comes up because in the previous snippet I was able to access the static "enemy" function with the help of an instance of the class but here it's proving false. I mean why can't I access the ".class" static method with the help of the instance of the class. Am I wrong to consider ".class" to be a static function or member of the class Janerio and is it wrong to be analogous to the static features of both the snippets?
But as soon as I call the ".class" with the class name things appear to be that ".class" is static in nature but it deviates to the be static on calling ".class" with an instance of the class.
public class Janerio {
public static void main(String[] args) {
System.out.println(Janerio.class);
}
}
Output we get:
class Janerio
.class references the Class object that represents the given class. it is used when there isn't an instance variable of the class. Hence it doesn't apply to your usage
Read more here:
https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.8.2
With .class you do not select a field (besides class is a keyword).
It is a pseudo operation, usable with a class name, yielding a Class instance:
int.class, Integer.class, java.util.List.class
Am I wrong to consider ".class" to be a static function or member of the class Janerio?
Yes, it's not a variable and it's definitely not a method. You have to use the Object#getClass method when you want to get the class of an instance.
Yes, you can access these static members of classes that way, but the better practise is to use name of that class instead of the name of specific referece to object of that class. It makes your code clearer to understand and to read as static members of class do not belong to specific object but to whole class. For example:
class MyClass {
static int count = 0;
}
It is better to access this field that way:
MyClass.field = 128;
instead of changing that value using the name of specific reference, for example:
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
obj1.field = 128;
Because it can be confusing when you realize that this way even obj2.field has assigned new value of 128. It might look a bit tricky, so again, I would suggest the first presented method of calling methods or changing values assigned to fields.
Alright, so I have a driver class and an arraylist (as you can probably guess).
My arraylist is full of strings and I'm accessing it through a getter that I've created in my other class.
It says that "The static method getMouseList() from the type Desktop should be accessed in a static way". How should I go about fixing this? Do you see any other errors?
Thanks to everyone who can help!
So here's my code:
Class:
static ArrayList <String> Strings;
public static void main(String[] args) {
Strings = new ArrayList <String>();
Strings.add("goodbye");
Strings.add("hi");
Strings.add("hello");
}
public static ArrayList<String> getStrings() {
return Strings;
}
Driver class:
Desktop test4 = new Desktop();
System.out.println(test4.getStrings());
Since it's static, it belongs to its class, not to a class instance. Thus, you need to access it using the class: Desktop.getStrings()
UPDATE
I'd need to see more of your code to exactly explain what's going on. So, I'll try to explain on what I imagine is your code. Please note that Java programs start from one main method. Depending on how you execute your program, one of them is going to be invoked, the others will not.
In any case, one way would be to create another static method in Desktop and move the initialization code from main to that method, such as:
public static void initializeStrings(){
Strings = new ArrayList <String>();
Strings.add("goodbye");
Strings.add("hi");
Strings.add("hello");
}
Then, make sure that you call that method, via Desktop.initializeStings(); before trying to access the Strings array (for example in the start of the actual main method of your program.
EDIT 2:
OK, so your main should now look something like this:
public static void main(String[] args) {
Desktop.initializeStrings();
Driver.doSomething();
}
and your Driver's method (inside Driver class):
public static void doSomething() {
//some code
//strings are initialized and will get printed
System.out.println(Desktop.getStrings());
}
That should give you a hint on how to move forward. On a side note, all this staticness is hindering the Object oriented nature of Java. I would suggest a tutorial in Java's object oriented programming model: https://docs.oracle.com/javase/tutorial/java/index.html
So I've created an array in the main method that reads an input from a file and then adds it to the array and it also uses a command reader to check that the file has data left. How do I make any specific array element available to use in other methods? Take an array called array[], how do I access array[1] and use it in other methods? Thanks and sorry if this is an obvious question but I'm quite new to java.
Edit
Source code:
import java.io.File;
// Reads commands from input file
public class Example {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("No args given.");
System.exit(1);
}
// reads every argument given as a filename
for (String filename : args) {
File file = new File(filename);
//creating a command reader from a file
CommandReader Reader = new CommandReader(file);
// reads every line of the file
while(Reader.hasNext()) {
// gets the given command from the next line
String[] command = reader.next();
}
}
}
}
I want to use these outside of the main class. I've got a command reader class that formats them in such a way as to give the commands like that but that is not important to using the array outside of the main. Thanks
command[0] => "add"
command[1] => "AlbinoMilk's great adventure"
command[2] => "AlbinoMilk"
command[3] => "250"
The keyword here is scope. The scope of a variable defines, where the variable is visible and can be used. Usually, the scope of a variable in Java is defined to be the innermost curly braces that are surrounding the variable definition.
There are several ways to be able to access variables outside of their current scope.
When you call a method from somewhere with access to the variable, add the variable as parameter to the method. This way, the function also has access.
Move the definition of the variable. For instance, if you have a local variable in your main, just move it one "level" up, so define it as a (private) member of the class instead. Now, all the functions in your class have access to it. This should only be done if it helps the class in the future or makes code more readable. Usually, try to keep the scope of variables as small as possible to increase maintainability.
Have a variable access controller class. Classes can then register access of certain variables through interface implementations. Other classes can then access variables through this interface.
etc.
In your case, it is best to go with the first (or second) way.
Just pass it as a parameter to the other functions.
foo(int[] array) {//}
And call it from the main
foo(array1);
There are two ways to achieve that:
declare your array as a field in your class, outside the main method:
public class SomeClass {
private int[] array;
...
...
public static void main(String[] args) {
array = ....
}
...
}
pass it as a parameter to other methods that require it
In my case I had an ArrayList in my main method as follows: static ArrayList<MyClass> myclass= new ArrayList<MyClass>();. I was adding random values to it from the main method. Then I needed to access the ArrayList from another class so the way to do that, was to create a constructor in the class where I wanted to use it like this:
ArrayList<MyClass> myclass;
public AnotherClass(ArrayList<MyClass> myclass) {
this.myclass= myclass;
}
// the ArrayList used in other methods here
So I could create objects of AnotherClass in main taking the ArrayList as an argument: AnotherClass ac = new AnotherClass(myClass);
I don't understand why methods on arrays, in Java, have to be static. Static methods can only be used on static variables right? So this would mean arrays are static variables, variables shared by a class? But what class would this be?
Can someone help me understand this?
Edit: to be more specific, I am creating methods to act on arrays but if I just write "public int[] expandArr(int[]a, int v)" and I try to use this method in the main method, I get an error saying I can't make a static reference to a non-static method. When I write "public static int[] expandArr(int[]a, int v)" it works then.
I understand you cannot change the size of an array, the method I wrote makes a new array with increased size and copies the first one into it.
Thank you.
You say you tried to write this:
public int[] expandArr(int[]a, int v)
The thing is, you had to write it in some class, since you can't just have free-floating methods in your program. Therefore, it must operate on a instance of the class. For example:
public class MyProgram {
public int[] expandArr(int[]a, int v) { ... }
public static void main(String[] args) { ... }
}
expandArr requires an instance of MyProgram, since you didn't declare it to be static. And that has nothing to do with arrays. It would be the same if you wrote
public class MyProgram {
public String expandString(String s, int v) { ... }
public static void main(String[] args) {
String s = expandString(args[0], 1); // ILLEGAL
String s2 = args[0].expandString(1); // ILLEGAL
}
}
Although the first parameter of expandString is a String, this actually operates on a MyProgram, and you cannot use expandString without an instance of MyProgram to operate on. Making it static means that you can (the first use of expandString in my example would become legal.)
In general, you can't add methods to a class without modifying the source of that class. If you want to write a new method that does something with objects of a certain class C, and you can't modify class C (perhaps because it's in the Java library or someone else's library), then you'll need to put the method in some other class C2, and most of the time you will need to make the method static since it doesn't involve objects of class C2.
You can't call a non-static method from a static method unless you first instantiate the an object of the class.
e.g.
In class Whatever...
public boolean ok() {
return true;
}
public static void main(String[] args) {
Whatever w = new Whatever();
System.out.println(w.ok());
}
You cant call a non static method from a static context. A static method belongs to the class, non static or instance methods are copied to each instance of the class (they each have their own). If I have 10 instances of class A, and class A has a static method, which all of them share, then I try to invoke a non static method in class A from class A's static method, which instance of class A gets its method invoked? The behavior is undefined.
The question really has nothing to do with arrays.
This question is related: Can't call non static method
I think what you're referring to is the fact that you can't extend an array class and hence can't add a method to it:
// No way to do this
int[] array;
array.myMethod();
This means your only option is to make a static helper method somewhere:
// So you have to do this
int[] array;
Utils.myMethod(array);
class Utils {
static void myMethod(int[] array) {
...
}
}
An example of this is the Arrays class, which has lots of static methods for operating on arrays. Conceptually it would be clearer if these methods could be added to the array classes, but you can't do that in Java (you can in other languages like Javascript).
That is why we use other classes like the ArrayList to make them grow dynamically in size. At the core of an arraylist you will simply find an array that is renewed in size whenever the class figures out it necessary. If I'm understanding your question right.
Complete beginner here. I am trying to call a method from a class to run in the main class. But I cannot seem to figure out why it is not work. Here is how I am calling the class
public static void main(String[] args) {
findMP3Tracks FT = new findMP3Tracks();
FT.findMP3();
This is the class method i want to call
public static List<String> findMP3(String p)
{
List<String> foundMP3Tracks = new ArrayList<>();
try (DirectoryStream<Path> folderContents = Files.newDirectoryStream(Paths.get(p)))
{
//Look for
for (Path folderItem: folderContents){
if(Files.isDirectory(folderItem, LinkOption.NOFOLLOW_LINKS)) {
foundMP3Tracks.addAll(findMP3(folderItem.toString()));
}
else if(isValidMP3(folderItem.toString())) {
foundMP3Tracks.add(folderItem.toString());
}
}
}
Assuming findMP3(String) is a method inside the class findMP3Tracks (I would recommend you to follow Java conventions for class names), you may call it in the main as:
public static void main(String[] args) {
...
List<String> result = findMP3Tracks.findMP3("Name of MP3");
}
You may use the name of the class findMP3Tracks to invoke the method findMP3, because it is declared as static. So it's not necessary to create an instance to call it. (Of course you may want to create instances of that class for other operations)
Also, since findMP3 is returning a List<String>, you may want to store it in a variable (In the example result)
First, you don't need instances to call a static method, so this line
findMP3Tracks FT = new findMP3Tracks();
is useless, you can remove it.
Use (for example)
findMP3Tracks.findMP3("Some MP3 name");
Also you need to get the returned value, so it should be:
final List<String> mp3List = findMP3Tracks.findMP3("Some MP3 name");
PS: in Java by convention class names start with uppercase, I suggest you change findMP3Tracks class name to FindMP3Tracks
You've declared the method as
public static List<String> findMP3(String p)
which means (among other things) that when you call it, you're going to pass in a String argument. But you wrote
FT.findMP3();
where you're not passing in any argument at all. Something like
FT.findMP3("Hello");
would compile; or if you had a String variable whose value was the name of the MP3 that you wanted to search for, you could use that too. But the call to any method MUST match the declaration of that method.
The method findMP3 is declared as static. Static variables and methods are members of the class.
You can invoke it directly using the classname. So, it should be findMP3Tracks.findMP3()
Also, a word about the static method. If you do know that the behaviour of the method isnt different for different instances, then you might/can declare it as static. Although, it is a design decision that you would make. If it does behave differently based on the passed in parameter, it is better off to have a method which isnt static.