Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to access the DefaultHashMap class but getting error in the main method. Could anyone please tell me what is the problem?
import java.util.Random;
import java.util.*;
public class PythonToJava {
public static void main(String[] args) {
Random rm = new Random();
int i = rm.nextInt(1000);
HashMap<Integer,Integer> stats = new HashMap<Integer,Integer>();
DefaultHashMap<K,V> default = new DefaultHashMap<K,V>();
System.out.println("Random Number Generated is: " + i);
for (int j = 0; j<i; j++){
int value = rm.nextInt(500);
System.out.println("The value of VALUE is " + value);
}
}
}
class DefaultHashMap<K,V> extends HashMap<K,V> {
protected V defaultValue;
public DefaultHashMap(V defaultValue) {
this.defaultValue = defaultValue;
}
#Override
public V get(Object k) {
V v = super.get(k);
return ((v == null) && !this.containsKey(k)) ? this.defaultValue : v;
}
}
Please help me in rectifying the errors I'm encountering at the line with the code:
DefaultHashMap<K,V> default = new DefaultHashMap<K,V>();
The K and V are type parameters, and here, you need to use concrete types to substitute them, the same as when you are using HashMap.
K,V has to be objects
You cannot use variable default. Its a java reserve word.
You should read about java generics
http://docs.oracle.com/javase/tutorial/java/generics/why.html
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
Basically need to create a class which is custom type that has two integers: -1 and 1, instead of all the integers that exist.
If you would suggest using enum (never implemented before), could you please suggest how would that work.
public class PlusOrMinusOne{
private int plusOne=1;
private int minusOne=-1;
}
Java does not let you write your own primitives, and does not have operator overloading. It is therefore simply impossible to have a class such that any expressions that are of that type act like a number. In other words, given:
PlusOrMinusOne a = ...;
int b = a + 1; // cannot be made to work
if (a == -1) // cannot be made to work
What you can do is simply create 2 instances such that they are the only instances of a given class. One of them is the value associated with +1, the other with -1. There is nothing specific about these 2 instances that reflects that they represent -1 or +1 - you can code them however you like.
enum is the general way to do this - it takes care of ensuring nobody can make instances other than the ones you defined, for example.
public enum PlusOrMinusOne /* horrible name, come up with a better one */ {
PLUS_ONE(+1),
MINUS_ONE(-1),
;
private final int value;
PlusOrMinusOne(int value) {
this.value = value;
}
public static PlusOrMinusOne of(int value) {
if (value == -1) return MINUS_ONE;
if (value == +1) return PLUS_ONE;
throw new IllegalArgumentException("" + value);
}
public int getValue() {
return value;
}
public PlusOrMinusOne neg() {
if (this == PLUS_ONE) return MINUS_ONE;
return PLUS_ONE;
}
public String toString() {
return this == PLUS_ONE ? "+1" : "-1";
}
}
When using enums you can define custom fields, so in your case you can do for example:
public enum CustomNumber {
PLUS_ONE(1),
MINUS_ONE(-1);
public final int value;
CustomNumber(int value) {
this.value = value;
}
}
public static void main(String[] args) {
System.out.println(CustomNumber.MINUS_ONE.value);
System.out.println(CustomNumber.PLUS_ONE.value);
}
enum PlusOrMinusOne {
PLUS_ONE(1),
MINUS_ONE(-1);
public final int num;
PlusOrMinusOne(int num) {
this.num = num;
}
}
public static void main(String[] args) {
System.out.println(CustomNumber.MINUS_ONE.num);
System.out.println(CustomNumber.PLUS_ONE.num);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
My Instructor for my Data structures class has told me that there is a better way to implement using a Generic Data type in this method instead of casting everything to E. I am unable to figure out how this better way is implemented or exactly what she means. I know this method I wrote works but if there is a better way I would like to know.
public class GenericSortedArrayBag<E extends Comparable> implements Cloneable,Iterable<E> {
public int numPresents;
public int maxPresents;
private Object[] data;
public void delete(E k) {
boolean found = false;
for(int i=0; i <numPresents; i++) {
if(((E)data[i]).equals(k)) {
found = true;
}
if(found && i<numPresents - 1) {
data[i] = data[i+1];
}
else if(found) {
data[i] = null;
}
}
numPresents--;
}
Instead of
private Object[] data;
you can use
private E[] data;
That way you save the cast
if((data[i]).equals(k))
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am writing a java method which runs through an array and if a value is present, then it returns the index of the value. It is not compiling, but I don't know what part of my code isn't comprehensive.
import java.util.*;
import static java.lang.System.out;
public class Lab26 {
public static void main(String[] args) {
}
public static int simpleSearch(int[] nums, int value) {
int nul = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == value) {
return i;
}
}
}
}
What if if (nums[i] == value) is never satisfied? You will not return anything but the method signature expects you to return an int.
in simpleSearch method, return an integer at the end.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have started to learn Java lambda and I do not understand it. I found an example.
String[] atp = {"Rafael Nadal", "Novak Djokovic", "Stanislas Wawrinka", "David Ferrer", "Roger Federer", "Andy Murray", "Tomas Berdych", "Juan Martin Del Potro"};
players.forEach((player) -> System.out.print(player + "; "));
And it works fine, but my code does not work.
public class Counter {
String[] atp = {"Rafael Nadal", "Novak Djokovic", "Stanislas Wawrinka", "David Ferrer", "Roger Federer", "Andy Murray", "Tomas Berdych", "Juan Martin Del Potro"};
List<String> players = Arrays.asList(atp);
private int a = 7;
private int b = 7;
public int summ(int a, int b) {
return a + b;
}
public void print(){
players.forEach((player) -> System.out.print(player + "; "));
summ((a,b)-> System.out.print(a + b));
}
}
I want understand how lambda works.
This is not working -
summ((a,b)-> System.out.print(a + b));
You can use lambdas with functional interfaces.
What is a functional interface?
It is basically an interface that has one and only abstract method (but can have other default methods for example)
The most frequent example is the Predicate interface.
public interface Predicate <T> {
boolean test(T t);
// Other methods
}
This one take any Object (generics) and returns a boolean primitive.
So let's say we want to test a condition using this interface to find pair numbers in a loop, we code the following.
Predicate<Integer> function = a -> a%2 == 0;
for (int i = 0 ; i < 10 ; i++){
if (function.test(i)){ // The primitive is AutoBoxed into an Integer Object here
System.out.println(i);
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hello my problem is that
DepositoBancario(String s){
String[]v = s.split("[ :]");
Integer n= v.length;
if(n!=2) throw new IllegalArgumentException("Error"+s);
banco= new String(v[0]);
interes= new List(v[1]);
}
This constructor is for be able to build and object by a file and I want transform the element v[1] in List(interes).
Thanks for your help guys.
You don't need to create a String with new String("") you can just set banco = v[0]
List is an Interface and can not be instantiated via a constructor. What you need is a ArrayList for example. But this class doesn't have a Constructor for a Strign neither. What is in that String v[1]?
I believe you have one or more elements (interes) and you wants to convert them into list of elements. You can use something like this.
import java.util.ArrayList;
import java.util.List;
public class DepositoBancario {
String banco;
List<String> interes;
public DepositoBancario(String s){
String[]v = s.split("[ :]");
Integer n= v.length;
if(n!=2) throw new IllegalArgumentException("Error"+s);
banco= v[0];
if(v[1] != null){
interes = new ArrayList<String>();
}
for(int i=1;i<n;i++)
interes.add(v[i]);
}
}
Note : Please consider the suggestion of markusw they are valuable.
First, You code won't compile unless You are using some custom implementation of List.
For what I can understand from You question it should be something like
import java.util.List;
import java.util.ArrayList;
public class DepositoBancario {
private String banco;
private List<String> interes;
DepositoBancario(String s) {
String[]v = s.split("[ :]"); // split input string by colon or space
if(v.length != 2) { // check if there are just two fields
throw new IllegalArgumentException("Invalid syntax, two fields expected: " + s);
}
banco = v[0];
interes = new ArrayList<String>();
interes.add(v[1]);
}
}