Search Results

Search found 33640 results on 1346 pages for 'java generics'.

Page 79/1346 | < Previous Page | 75 76 77 78 79 80 81 82 83 84 85 86  | Next Page >

  • Extract Generic types from extended Generic

    - by Brigham
    I'm trying to refactor a class and set of subclasses where the M type does extend anything, even though we know it has to be a subclass of a certain type. That type is parametrized and I would like its parametrized types to be available to subclasses that already have values for M. Is there any way to define this class without having to include the redundant K and V generic types in the parameter list. I'd like to be able to have the compiler infer them from whatever M is mapped to by subclasses. public abstract class NewParametrized<K, V, M extends SomeParametrized<K, V>> { public void someMethodThatTakesKAndV(K k1, V v1) { } } In other words, I'd like the class declaration to look something like: public class NewParametrized<M extends SomeParametrized<K, V>> { And K and V's types would be inferred from the definition of M.

    Read the article

  • Type-safe mapping from Class<T> to Thing<T>

    - by Joonas Pulakka
    I want to make a map-kind of container that has the following interface: public <T> Thing<T> get(Class<T> clazz); public <T> void put(Class<T> clazz, Thing<T> thing); The interesting point is that the Ts in each Class<T><- Thing<T> pair is the same T, but the container should be able to hold many different types of pairs. Initially I tried a (Hash)Map. But, for instance, Map<Class<T>, Thing<T>> is not right, because then T would be same T for all pairs in that map. Of course, Map<Class<?>, Thing<?>> works, but then I don't have type-safety guarantees so that when I get(String.class), I can't be sure that I get a Thing<String> instance back. Is there a way to accomplish the kind of type safety that I'm looking for?

    Read the article

  • Constraint Validation

    - by tanuja
    I am using javax.validation.Validator and relevant classes for annotation based validation. Configuration<?> configuration = Validation.byDefaultProvider().configure(); ValidatorFactory factory = configuration.buildValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<ValidatableObject>> constraintViolations = validator.validate(o); for (ConstraintViolation<ValidatableObject> value : constraintViolations) { List< Class< ? extends ConstraintValidator< ? extends Annotation,?>>> list = value.getConstraintDescriptor().getConstraintValidatorClasses(); } I get a compilation error stating: Type mismatch: cannot convert from List< Class< ? extends ConstraintValidator< capture#4-of ?,? to List< Class< ? extends ConstraintValidator< ? extends Annotation,? What am I missing?

    Read the article

  • Java InputStream encoding/charset

    - by Tobbe
    Running the following (example) code import java.io.*; public class test { public static void main(String[] args) throws Exception { byte[] buf = {-27}; InputStream is = new ByteArrayInputStream(buf); BufferedReader r = new BufferedReader(new InputStreamReader(is, "ISO-8859-1")); String s = r.readLine(); System.out.println("test.java:9 [byte] (char)" + (char)s.getBytes()[0] + " (int)" + (int)s.getBytes()[0]); System.out.println("test.java:10 [char] (char)" + (char)s.charAt(0) + " (int)" + (int)s.charAt(0)); System.out.println("test.java:11 string below"); System.out.println(s); System.out.println("test.java:13 string above"); } } gives me this output test.java:9 [byte] (char)? (int)63 test.java:10 [char] (char)? (int)229 test.java:11 string below ? test.java:13 string above How do I retain the correct byte value (-27) in the line-9 printout? And consequently receive the expected output of the System.out.println(s) command (å).

    Read the article

  • Java Compiler Creation Help..Please

    - by Brian
    I need some help with my code here...What we are trying to do is make a compiler that will read a file containing Machine Code and converting it to 100 lines of 4 bits example: this code is the machine code being converting to opcode and operands. I need some help please.. thanks 799 798 198 499 1008 1108 899 909 898 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Everything compiles but when I go and run my Test.java I get the following OutPut: Exception in thread "main" java.util.NoSuchElementException: No line found at java.util.Scanner.nextLine(Scanner.java:1516) at Compiler.FirstPass(Compiler.java:22) at Compiler.compile(Compiler.java:11) at Test.main(Test.java:5) Here is my class Compiler: import java.io.*; import java.io.DataOutputStream; import java.util.NoSuchElementException; import java.util.Scanner; class Compiler{ private int lc = 0; private int dc = 99; public void compile(String filename) { SymbolList symbolTable = FirstPass(filename); SecondPass(symbolTable, filename); } public SymbolList FirstPass(String filename) { File file = new File(filename); SymbolList temp = new SymbolList(); int dc = 99; int lc = 0; try{ Scanner scan = new Scanner(file); String line = scan.nextLine(); String[] linearray = line.split(" "); while(line!=null){ if(!linearray[0].equals("REM")){ if(!this.isInstruction(linearray[0])){ linearray[0]=removeColon(linearray[0]); if(this.isInstruction(linearray[1])){ temp.add(new Symbol(linearray[0], lc, null)); lc++; } else { temp.add(new Symbol(linearray[0], dc, Integer.valueOf((linearr\ ay[2])))); dc--; } } else { if(!linearray[0].equals("REM")) lc++; } } try{ line = scan.nextLine(); } catch(NoSuchElementException e){ line=null; break; } linearray = line.split(" "); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return temp; } public String makeFilename(String filename) { return filename + ".ex"; } public String removeColon(String str) { if(str.charAt(str.length()-1) == ':'){ return str.substring(0, str.length()-1); } else { return str; } } public void SecondPass(SymbolList symbolTable, String filename){ try { int dc = 99; //Open file for reading File file = new File(filename); Scanner scan = new Scanner(file); //Make filename of new executable file String newfile = makeFilename(filename); //Open Output Stream for writing new file. FileOutputStream os = new FileOutputStream(filename); DataOutputStream dos = new DataOutputStream(os); //Read First line. Split line by Spaces into linearray. String line = scan.nextLine(); String[] linearray = line.split(" "); while(scan.hasNextLine()){ if(!linearray[0].equals("REM")){ int inst=0, opcode, loc; if(isInstruction(linearray[0])){ opcode = getOpcode(linearray[0]); loc = symbolTable.searchName(linearray[1]).getMemloc(); inst = (opcode*100)+loc; } else if(!isInstruction(linearray[0])){ if(isInstruction(linearray[1])){ opcode = getOpcode(linearray[1]); if(linearray[1].equals("STOP")) inst=0000; else { loc = symbolTable.searchName(linearray[2]).getMemloc(); inst = (opcode*100)+loc; } } if(linearray[1].equals("DC")) dc--; } System.out.println(inst); dos.writeInt(inst); linearray = line.split(" "); } if(scan.hasNextLine()) { line = scan.nextLine(); } } scan.close(); for(int i = lc; i <= dc; i++) { dos.writeInt(0); } for(int i = dc+1; i<100; i++){ dos.writeInt(symbolTable.searchLocation(i).getValue()); if(i!=99) dos.writeInt(0); } dos.close(); os.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public int getOpcode(String inst){ int toreturn = -1; if(isInstruction(inst)){ if(inst.equals("STOP")) toreturn=0; if(inst.equals("LD")) toreturn=1; if(inst.equals("STO")) toreturn=2; if(inst.equals("ADD")) toreturn=3; if(inst.equals("SUB")) toreturn=4; if(inst.equals("MPY")) toreturn=5; if(inst.equals("DIV")) toreturn=6; if(inst.equals("IN")) toreturn=7; if(inst.equals("OUT")) toreturn=8; if(inst.equals("B")) toreturn=9; if(inst.equals("BGTR")) toreturn=10; if(inst.equals("BZ")) toreturn=11; return toreturn; } else { return -1; } } public boolean isInstruction(String totest){ boolean toreturn = false; String[] labels = {"IN", "LD", "SUB", "BGTR", "BZ", "OUT", "B", "STO", "STOP", "AD\ D", "MTY", "DIV"}; for(int i = 0; i < 12; i++){ if(totest.equals(labels[i])) toreturn = true; } return toreturn; } } And here is my class Computer: import java.io.*; import java.util.NoSuchElementException; import java.util.Scanner; class Computer{ private Cpu cpu; private Input in; private OutPut out; private Memory mem; public Computer() throws IOException { Memory mem = new Memory(100); Input in = new Input(); OutPut out = new OutPut(); Cpu cpu = new Cpu(); System.out.println(in.getInt()); } public void run() throws IOException { cpu.reset(); cpu.setMDR(mem.read(cpu.getMAR())); cpu.fetch2(); while (!cpu.stop()) { cpu.decode(); if (cpu.OutFlag()) OutPut.display(mem.read(cpu.getMAR())); if (cpu.InFlag()) mem.write(cpu.getMDR(),in.getInt()); if (cpu.StoreFlag()) { mem.write(cpu.getMAR(),in.getInt()); cpu.getMDR(); } else { cpu.setMDR(mem.read(cpu.getMAR())); cpu.execute(); cpu.fetch(); cpu.setMDR(mem.read(cpu.getMAR())); cpu.fetch2(); } } } public void load() { mem.loadMemory(); } } Here is my Memory class: import java.io.*; import java.util.NoSuchElementException; import java.util.Scanner; class Memory{ private MemEl[] memArray; private int size; private int[] mem; public Memory(int s) {size = s; memArray = new MemEl[s]; for(int i = 0; i < s; i++) memArray[i] = new MemEl(); } public void write (int loc,int val) {if (loc >=0 && loc < size) memArray[loc].write(val); else System.out.println("Index Not in Domain"); } public int read (int loc) {return memArray[loc].read(); } public void dump() { for(int i = 0; i < size; i++) if(i%1 == 0) System.out.println(memArray[i].read()); else System.out.print(memArray[i].read()); } public void writeTo(int location, int value) { mem[location] = value; } public int readFrom(int location) { return mem[location]; } public int size() { return mem.length; } public void loadMemory() { this.write(0, 799); this.write(1, 798); this.write(2, 198); this.write(3, 499); this.write(4, 1008); this.write(5, 1108); this.write(6, 899); this.write(7, 909); this.write(8, 898); this.write(9, 0000); } public void loadFromFile(String filename){ try { FileReader fr = new FileReader(filename); BufferedReader br = new BufferedReader(fr); String read=null; int towrite=0; int l=0; do{ try{ read=br.readLine(); towrite = Integer.parseInt(read); }catch(Exception e){ } this.write(l, towrite); l++; }while(l<100); }catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } Here is my Test class: public class Test{ public static void main(String[] args) throws java.io.IOException { Compiler compiler = new Compiler(); compiler.compile("program.txt"); } }

    Read the article

  • How to use Comparator in Java to sort

    - by Dan
    I learned how to use the comparable but I'm having difficulty with the Comparator. I am having a error in my code: Exception in thread "main" java.lang.ClassCastException: New.People cannot be cast to java.lang.Comparable at java.util.Arrays.mergeSort(Unknown Source) at java.util.Arrays.sort(Unknown Source) at java.util.Collections.sort(Unknown Source) at New.TestPeople.main(TestPeople.java:18) Here is my code: import java.util.Comparator; public class People implements Comparator{ private int id; private String info; private double price; public People(int newid, String newinfo, double newprice){ setid(newid); setinfo(newinfo); setprice(newprice); } public int getid() { return id; } public void setid(int id) { this.id = id; } public String getinfo() { return info; } public void setinfo(String info) { this.info = info; } public double getprice() { return price; } public void setprice(double price) { this.price = price; } public int compare(Object obj1, Object obj2) { Integer p1 = ((People)obj1).getid(); Integer p2 = ((People)obj2).getid(); if (p1 p2 ){ return 1; } else if (p1 < p2){ return -1; } else return 0; } } import java.util.ArrayList; import java.util.Collections; public class TestPeople { public static void main(String[] args) { ArrayList peps = new ArrayList(); peps.add(new People(123, "M", 14.25)); peps.add(new People(234, "M", 6.21)); peps.add(new People(362, "F", 9.23)); peps.add(new People(111, "M", 65.99)); peps.add(new People(535, "F", 9.23)); Collections.sort(peps); for(int i=0;i I believe it has to do something with the casting in the compare method but I was playing around with it and still could not find the solution

    Read the article

  • Java conditional compilation: how to prevent code chunks to be compiled?

    - by khachik
    My project requires Java 1.6 for compilation and running. Now I have a requirement to make it working with Java 1.5 (from the marketing side). I want to replace method body (return type and arguments remain the same) to make it compiling with Java 1.5 without errors. Details: I have an utility class called OS which encapsulates all OS-specific things. It has a method public static void openFile(java.io.File file) throws java.io.IOException { // open the file using java.awt.Desktop ... } to open files like with double-click (start Windows command or open Mac OS X command equivalent). Since it cannot be compiled with Java 1.5, I want to exclude it during compilation and replace by another method which calls run32dll for Windows or open for Mac OS X using Runtime.exec. Question: How can I do that? Can annotations help here? Note: I use ant, and I can make two java files OS4J5.java and OS4J6.java which will contain the OS class with the desired code for Java 1.5 and 1.6 and copy one of them to OS.java before compiling (or an ugly way - replace the content of OS.java conditionally depending on java version) but I don't want to do that, if there is another way. Elaborating more: in C I could use ifdef, ifndef, in Python there is no compilation and I could check a feature using hasattr or something else, in Common Lisp I could use #+feature. Is there something similar for Java? Found this post but it doesn't seem to be helpful. Any help is greatly appreciated. kh.

    Read the article

  • Type mismatch: cannot convert from ArrayList<Data> to MyCollection

    - by Tommy
    I've read similar questions here but I'm still a little confused. MyCollection extends ArrayList<MyClass> MyClass implements Data yet this gives me the "cannot convert from ArrayList to MyCollection" MyCollection mycollection = somehandler.getCollection(); where getCollection looks like this public ArrayList<Data> getCollection() So my assumptions are obviously wrong. How can I make this work like I would like it to

    Read the article

  • Does collections type conversion util methods already exist in any API?

    - by Delta
    interface TypeConverter<T, E> { T convert(E e); } class CollectionUtil() { public static <E> List<T> convertToList(List<E> fromList, TypeConverter<T, E> conv) { { if(fromList== null) return null; List<T> newList = new ArrayList<T>(fromList.size()) for(E e : fromList) { newList.add(conv.convert(e)); } return newList; } } Above code explains converting from List of String to List of Integer by implementing TypeConverter interface for String, Integer. Are there already any collections conversion utility methods exists in any API like list to set and so on?

    Read the article

  • How do I create a new AnyType[] array?

    - by cb
    Which is the best practice in this situation? I would like an un-initialized array of the same type and length as the original. public static <AnyType extends Comparable<? super AnyType>> void someFunction(AnyType[] someArray) { AnyType[] anotherArray = (AnyType[]) new Comparable[someArray.length]; ...or... AnyType[] anotherArray = (AnyType[]) new Object[someArray.length]; ...some other code... } Thanks, CB

    Read the article

  • Getting class Type information for Elements on a collection

    - by DutrowLLC
    I would like to get gain access to the type of Object held in a Collection. Below is a simplified example of when and why I might want to do this. Is this even possible? List<Address> addressList = new LinkedList<Address>(); Main.addElement(addressList); Class Main{ public void addElement(Object inArgument){ List<Object> argument = (List<Object>)inArgument; argument.add( /* WOULD LIKE TO CREATE A NEW OBJECT OF THE APPROPRIATE TYPE HERE, IN THIS CASE, IT WOULD BE OF TYPE: "Address" */ ); } }

    Read the article

  • Returnimng collection of interfaces

    - by apoorv020
    I have created the following interface public interface ISolutionSpace { public boolean isFeasible(); public boolean isSolution(); public Set<ISolutionSpace> generateChildren(); } However, in the implementation of ISolutionSpace in a class called EightQueenSolutionSpace, I am going to return a set of EightQueenSolutionSpace instances, like the following stub: @Override public Set<ISolutionSpace> generateChildren() { return new HashSet<EightQueenSolutionSpace>(); } However this stub wont compile. What changes do I need to make? EDIT: I tried 'HashSet' as well and had tried using the extends keyword. However since 'ISolutionSpace' is an interface and EightQueenSolutionSpace is an implementation(and not a subclass) of 'ISolutionSpace', it is still not working.

    Read the article

  • Creating parameterized type object using annonymous class

    - by Andrei Fierbinteanu
    This might be a stupid question, but I just saw a question asking how to create a Type variable for a generic type. The consensus seemed to be that you should have a dummy method returning that type, and then use reflection to get it (in this case he wanted Map<String, String>). Something like this : public Map<String, String> dummy() { throw new Error(); } Type mapStringString = Class.forName("ThisClass").getMethod("dummy").getGenericReturnType(); My question is, not having used reflection that much, couldn't you just do something like: Type mapStringString = new ParameterizedType() { public Type getRawType() { return Map.class; } public Type getOwnerType() { return null; } public Type[] getActualTypeArguments() { return new Type[] { String.class, String.class }; } }; Would this work? If not, why not? And what are some of the dangers/problems if it does (besides being able to return some Type like Integer<String> which is obviously not possible.

    Read the article

  • Getting the type of a parametrized class parameter?

    - by GuidoMB
    I have the following class public class MyClass<T> { public Class<T> getDomainClass() { GET THE CLASS OF T } } I've googled this problem and all the answers I could find told me to use getGenericSuperClass(), but the problem of this method is that I must have a second class that extends MyClass and I don't want to do this. What I need is to get the parametrized type of a concrete class?

    Read the article

  • Interface with generic parameters- can't get it to compile

    - by user997112
    I have an interface like so: public interface MyInterface<E extends Something1> { public void meth1(MyClass1<E> x); } and I have a subclass whose superclass implements the above interface: public class MyClass2<E extends Something1> extends Superclass{ public MyClass2(){ } public void meth1(MyClass1 x) { // TODO Auto-generated method stub } } superclass: public abstract class Superclass<E extends Something1> implements MyInterface{ MyClass1<E> x; protected E y; public Superclass(){ } } the problem is that the parameter for meth1() is supposed to be generic. If I do MyClass1 it doesn't like it and the only way I can get it to compile is by leaving out generic parameters- which feels wrong. What's going wrong?

    Read the article

  • returning a Void object

    - by Robert
    What is the correct way to return a Void type, when it isn't a primitive? Eg. I currently use null as below. interface B<E>{ E method(); } class A implements B<Void>{ public Void method(){ // do something return null; } }

    Read the article

  • Any way to make a generic List where I can add a type AND a subtype?

    - by user383178
    I understand why I cannot do the following: private class Parent { }; private class Child extends Parent { }; private class GrandChild extends Child { }; public void wontCompile(List<? extends Parent> genericList, Child itemToAdd) { genericList.add(itemToAdd); } My question is there ANY practical way to have a typesafe List where you can call add(E) where E is known to be only a Parent or a Child? I vaguely remember some use of the "|" operator as used for wildcard bounds, but I cannot find it in the spec... Thanks!

    Read the article

  • activating the class need help.... :)

    - by asm_debuger
    this is my code... i dont anderstend way the class dont work... import java.awt.BorderLayout; import java.awt.Button; import java.awt.Color; import java.awt.GridLayout; import java.awt.Panel; public class Caldesinger { public Panel p1=new Panel(); public Button[] arr=new Button[20]; public String[] name = {"9","8","7","6","5","4","3","2","1","0","+","-","*","/",".","cos","sin","=","pow"}; public Caldesinger() { for (int i = 0; i < arr.length; i++) { this.arr[i]=new Button(""+name[i]); } } public Panel getP1() { return p1; } public void setP1(Panel p1) { this.p1 = p1; } public Button[] getArr() { return arr; } public void setArr(Button[] arr) { this.arr = arr; } public Object c() { this.p1.setLayout(new GridLayout(4,15)); for (int i = 0; i < arr.length; i++) { arr[i].setBackground(Color.LIGHT_GRAY); arr[i].setForeground(Color.orange); p1.add(arr[i]); } this.p1.setLayout(new GridLayout(4,15)); return this; } } the class desinge the applet this is the main: import java.applet.Applet; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Mainapp extends Applet implements ActionListener { Caldesinger desinge=new Caldesinger (); public void init() { this.setLayout(new BorderLayout()); this.desinge.c(); } public void ActionPerformed(ActionEvent arg0) { for (int i = 0; i <20; i++) { if(arg0.getSource()== this.desinge.arr[i]); } } } way the method c does not work? the method desinge the applet

    Read the article

  • Finding the specific type held in an ArrayList<Object> (ie. Object = String, etc.)

    - by Christopher Griffith
    Say I have an ArrayList that I have cast to an ArrayList of objects. I know that all the objects that were in the ArrayList I cast were of the same type, but not what the type was. Now, if the ArrayList is not empty, I could take one of the objects in it and use the instanceof operator to learn what the actual type is. But what of the case where the ArrayList is empty? How do I determine what type Object actually is then? Is it possible?

    Read the article

  • Generic factory of generic containers

    - by Feuermurmel
    I have a generic abstract class Factory<T> with a method createBoxedInstance() which returns instances of T created by implementations of createInstance() wrapped in the generic container Box<T>. abstract class Factory<T> { abstract T createInstance(); public final Box<T> createBoxedInstance() { return new Box<T>(createInstance()); } public final class Box<T> { public final T content; public Box(T content) { this.content = content; } } } At some points I need a container of type Box<S> where S is an ancestor of T. Is it possible to make createBoxedInstance() itself generic so that it will return instances of Box<S> where S is chosen by the caller? Sadly, defining the function as follows does not work as a type parameter cannot be declared using the super keyword, only used. public final <S super T> Box<S> createBoxedInstance() { return new Box<S>(createInstance()); } The only alternative I see, is to make all places that need an instance of Box<S> accept Box<? extends S> which makes the container's content member assignable to S. Is there some way around this without re-boxing the instances of T into containers of type Box<S>? (I know I could just cast the Box<T> to a Box<S> but I would feel very, very guilty.)

    Read the article

  • can I get .class from generic type argument?

    - by Mike S
    I have the following class: public abstract class MyClass<T extends Object> { protected T createNewFromData(Reader reader){ GSON.fromJSON(reader,T.class); // T.class isn't allowed :( } } How do I pass a Class<T instance into there? Is there some wierd and wacky work around? Is there a way to get a Class<T reference other than from a pre-instantiated Object of type T? It won't let me do this either: T t = new T(); Class<T> klass = t.class; ANSWER BELOW Thanks to the accepted answer, here is the solution: Type type = new TypeToken<T>(){}.getType(); return gson.fromJson(reader, type);

    Read the article

< Previous Page | 75 76 77 78 79 80 81 82 83 84 85 86  | Next Page >