Search Results

Search found 547 results on 22 pages for 'hashmap'.

Page 12/22 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • Playing Multiple sounds at the same time in Android

    - by Wrapper
    I am unable to use the following to code to play multiple sounds/beeps simultaneously. In my onclicklistener I have added ... public void onClick(View v) { mSoundManager.playSound(1); mSoundManager.playSound(2); } ... But this plays only one sound at a time, sound with index 1 followed by sound with index 2. How can I play atleast 2 sounds simultaneously using this code whenever there is an onClick() event? public class SoundManager { private SoundPool mSoundPool; private HashMap<Integer, Integer> mSoundPoolMap; private AudioManager mAudioManager; private Context mContext; public SoundManager() { } public void initSounds(Context theContext) { mContext = theContext; mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0); mSoundPoolMap = new HashMap<Integer, Integer>(); mAudioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE); } public void addSound(int Index,int SoundID) { mSoundPoolMap.put(1, mSoundPool.load(mContext, SoundID, 1)); } public void playSound(int index) { int streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC); mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, 0, 1f); } public void playLoopedSound(int index) { int streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC); mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, -1, 1f); } }

    Read the article

  • What are the hibernate annotations used to persist a value typed Map with an enumerated type as a ke

    - by Jason Novak
    I am having trouble getting the right hibernate annotations to use on a value typed Map with an enumerated class as a key. Here is a simplified (and extremely contrived) example. public class Thing { public String id; public Letter startLetter; public Map<Letter,Double> letterCounts = new HashMap<Letter, Double>(); } public enum Letter { A, B, C, D } Here are my current annotations on Thing @Entity public class Thing { @Id public String id; @Enumerated(EnumType.STRING) public Letter startLetter; @CollectionOfElements @JoinTable(name = "Thing_letterFrequencies", joinColumns = @JoinColumn(name = "thingId")) @MapKey(columns = @Column(name = "letter", nullable = false)) @Column(name = "count") public Map<Letter,Double> letterCounts = new HashMap<Letter, Double>(); } Hibernate generates the following DDL to create the tables for my MySql database create table Thing (id varchar(255) not null, startLetter varchar(255), primary key (id)) type=InnoDB; create table Thing_letterFrequencies (thingId varchar(255) not null, count double precision, letter tinyblob not null, primary key (thingId, letter)) type=InnoDB; Notice that hibernate tries to define letter (my map key) as a tinyblob, however it defines startLetter as a varchar(255) even though both are of the enumerated type Letter. When I try to create the tables I see the following error BLOB/TEXT column 'letter' used in key specification without a key length I googled this error and it appears that MySql has issues when you try to make a tinyblob column part of a primary key, which is what hibernate needs to do with the Thing_letterFrequencies table. So I would rather have letter mapped to a varchar(255) the way startLetter is. Unfortunately, I've been fussing with the MapKey annotation for a while now and haven't been able to make this work. I've also tried @MapKeyManyToMany(targetEntity=Product.class) without success. Can anyone tell me what are the correct annotations for my letterCounts map so that hibernate will treat the letterCounts map key the same way it does startLetter?

    Read the article

  • Is there a useDirtyFlag option for Tomcat 6 cluster configuration?

    - by kevinjansz
    In Tomcat 5.0.x you had the ability to set useDirtyFlag="false" to force replication of the session after every request rather than checking for set/removeAttribute calls. <Cluster className="org.apache.catalina.cluster.tcp.SimpleTcpCluster" managerClassName="org.apache.catalina.cluster.session.SimpleTcpReplicationManager" expireSessionsOnShutdown="false" **useDirtyFlag="false"** doClusterLog="true" clusterLogName="clusterLog"> ... The comments in the server.xml stated this may be used to make the following work: <% HashMap map = (HashMap)session.getAttribute("map"); map.put("key","value"); %> i.e. change the state of an object that has already been put in the session and you can be sure that this object still be replicated to the other nodes in the cluster. According to the Tomcat 6 documentation you only have two "Manager" options - DeltaManager & BackupManager ... neither of these seem to allow this option or anything like it. In my testing the default setup: <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/> where you get the DeltaManager by default, it's definitely behaving as useDirtyFlag="true" (as I'd expect). So my question is - is there an equivalent in Tomcat 6? Looking at the source I can see a manager implementation "org.apache.catalina.ha.session.SimpleTcpReplicationManager" which does have the useDirtyFlag but the javadoc comments in this state it's "Tomcat Session Replication for Tomcat 4.0" ... I don't know if this is ok to use - I'm guessing not as it's not mentioned in the main cluster configuration documentation.

    Read the article

  • Android - Loop Through strings.xml file

    - by Alexis Cartier
    I was wondering if there is anyway to loop through the strings.xml file. Let's say that I have the following format: <!-- FIRST SECTION --> <string name="change_password">Change Password</string> <string name="change_server">Change URL</string> <string name="default_password">password</string> <string name="default_server">http://xxx:8080</string> <string name="default_username">testPhoneAccount</string> <!-- SECOND SECTION --> <string name="debug_settings_category">Debug Settings</string> <string name="reload_data_every_startup_pref">reload_data_every_startup</string> <string name="reload_data_on_first_startup_pref">reload_data_on_first_startup</string> Now let's say I have this: private HashMap<String,Integer> hashmapStringValues = new HashMap<String, Integer>(); Is there a way to iterate only in the second section of my xml file? Maybe wrap the section with a tag like <section2> and then iterate through it? public void initHashMap(){ for (int i=0;i< ???? ;i++) //Here I need to loop only in the second section of my xml file { String nameOfTag = ? // Here I get the name of the tag int value = R.string.nameOfTag // Here I get the associated value of the tag this.hashmapStringValues.put(nameOfTag,value); } }

    Read the article

  • Are there any guarantees in JLS about order of execution static initialization blocks?

    - by Roman
    I wonder if it's reliable to use a construction like: private static final Map<String, String> engMessages; private static final Map<String, String> rusMessages; static { engMessages = new HashMap<String, String> () {{ put ("msgname", "value"); }}; rusMessages = new HashMap<String, String> () {{ put ("msgname", "????????"); }}; } private static Map<String, String> msgSource; static { msgSource = engMessages; } public static String msg (String msgName) { return msgSource.get (msgName); } Is there a possibility that I'll get NullPointerException because msgSource initialization block will be executed before the block which initializes engMessages? (about why don't I do msgSource initialization at the end of upper init. block: just the matter of taste; I'll do so if the described construction is unreliable)

    Read the article

  • XML parsing by DOM

    - by blackpearl
    NodeList nList2 = doc.getElementsByTagName("dep"); Map<String, List<Map<String, String>>> depMap = new HashMap<String, List<Map<String, String>>>(); for (int temp = 0; temp < nList2.getLength(); temp++) { Element el = (Element)nList2.item(temp); String type=el.getAttribute("type"); Node nNode = nList2.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; List<Map<String,String>> depList = new ArrayList<Map<String,String>>(); String governor = getTagValue("governor", eElement); String dependent = getTagValue("dependent", eElement); Map<String, String> govdepmap = new HashMap<String, String>(); govdepmap.put(governor, dependent); depList.add(govdepmap); List<Map<String,String>> flist = new ArrayList<Map<String,String>>(); flist.add(govdepmap); depMap.put(type, flist); } } I have the following structure in my XML file: going I Now i want to store the "idx" attribute of each "governor" and "dependent" tag. What code should I change or add?

    Read the article

  • How do I iterate over a collection that is in an object passed as parameter in a jasper report?

    - by spderosso
    Hi, I have an object A that has as an instance variable a collection of object Bs. Example: public class A{ String name; List<B> myList; ... public List<B> getMyList(){ return myList; } ... } I want this object to be the only source of information the jasper report gets, since all the information the report need is in A. I am currently doing something like: A myObjectA = new A(...); InputStream reportFile = MyPage.this.getClass().getResourceAsStream("test.jrxml"); HashMap<String, Object> parameters = new HashMap<String, Object>(); parameters.put("objectA", myObjectA); ... JasperReport report = JasperCompileManager.compileReport(reportFile); JasperPrint print = JasperFillManager.fillReport(report, parameters, new JRBeanCollectionDataSource(myObjectA.getMyList())); return JasperExportManager.exportReportToPdf(print); thereby passing "two" parameters, the objectA as a concrete parameter and the collection of object Bs that is in A as a bean data source. How do I iterate over the Bs in A by passing only A? Thanks!

    Read the article

  • Structuring input of data for localStorage

    - by WmasterJ
    It is nice when there isn't a DB to maintain and users to authenticate. My professor has asked me to convert a recent research project of his that uses Bespin and calculates errors made by users in a code editor as part of his research. The goal is to convert from MySQL to using HTML5 localStorage completely. Doesn't seem so hard to do, even though digging in his code might take some time. Question: I need to store files and state (last placement of cursor and active file). I have already done so by implementing the recommendations in another stackoverflow thread. But would like your input considering how to structure the content to use. My current solution Hashmap like solution with javascript objects: files = {}; // later, saving files[fileName] = data; And then storing in localStorage using some recommendations localStorage.setObject(files): Currently I'm also considering using some type of numeric id. So that names can be changed without any hassle renaming the key in the hashmap. What is your opinion on the way it is solved and would you do it any differently?

    Read the article

  • Java: Generics, Class.isaAssignableFrom, and type casting

    - by bguiz
    This method that uses method-level generics, that parses the values from a custom POJO, JXlistOfKeyValuePairs (which is exactly that). The only thing is that both the keys and values in JXlistOfKeyValuePairs are Strings. This method wants to taken in, in addition to the JXlistOfKeyValuePairs instance, a Class<T> that defines which data type to convert the values to (assume that only Boolean, Integer and Float are possible). It then outputs a HashMap with the specified type for the values in its entries. This is the code that I have got, and it is obviously broken. private <T extends Object> Map<String, T> fromListOfKeyValuePairs(JXlistOfKeyValuePairs jxval, Class<T> clasz) { Map<String, T> val = new HashMap<String, T>(); List<Entry> jxents = jxval.getEntry(); T value; String str; for (Entry jxent : jxents) { str = jxent.getValue(); value = null; if (clasz.isAssignableFrom(Boolean.class)) { value = (T)(Boolean.parseBoolean(str)); } else if (clasz.isAssignableFrom(Integer.class)) { value = (T)(Integer.parseInt(str)); } else if (clasz.isAssignableFrom(Float.class)) { value = (T)(Float.parseFloat(str)); } else { logger.warn("Unsupporteded value type encountered in key-value pairs, continuing anyway: " + clasz.getName()); } val.put(jxent.getKey(), value); } return val; } This is the bit that I want to solve: if (clasz.isAssignableFrom(Boolean.class)) { value = (T)(Boolean.parseBoolean(str)); } else if (clasz.isAssignableFrom(Integer.class)) { value = (T)(Integer.parseInt(str)); } I get: Inconvertible types required: T found: Boolean Also, if possible, I would like to be able to do this with more elegant code, avoiding Class#isAssignableFrom. Any suggestions? Sample method invocation: Map<String, Boolean> foo = fromListOfKeyValuePairs(bar, Boolean.class);

    Read the article

  • db4o problem with graph of objects

    - by Staszek28
    I am a new to db4o. I have a big problem with persistance of a graph of objects. I am trying to migrate from old persistance component to new, using db4o. Before I peristed all objects its graph looked like below (Take a look at Zrodlo.Metadane.abstrakt string field with focused value) [its view from eclipse debuger] with a code: ObjectContainer db=Db4o.openFile(DB_FILE); try { db.store(encja); db.commit(); } finally{ db.close(); } After that, I tried to read it with a code: ObjectContainer db=Db4o.openFile((DB_FILE)); try{ Query q = db.query(); q.constrain(EncjaDanych.class); ObjectSet<Object> objectSet = q.execute(); logger.debug("objectSet.size" + objectSet.size()); EncjaDanych encja = (EncjaDanych) objectSet.get(0); logger.debug("ENCJA" + encja.toString()); return encja; }finally{ db.close(); } and I got it (picture below) - string field "abstrakt" is null now !!! I take a look at it using ObjectManager (picture below) and abstrakt field has not-null value there!!! The same value, that on the 1st picture. Please help me :) It is my second day with db4o. Thanks in advance! I am attaching some code with structure of persisted class: public class EncjaDanych{ Map mapaIdRepo = new HashMap(); public Map mapaNazwaRepo = new HashMap(); }

    Read the article

  • Quickest way to compare a bunch of array or list of values.

    - by zapping
    Can you please let me know on the quickest and efficient way to compare a large set of values. Its like there are a list of parent codes(string) and each code has a series of child values(string). The child lists have to be compared with each other and find out duplicates and count how many times they repeat. code1(code1_value1, code1_value2, code3_value3, ..., code1_valueN); code2(code2_value1, code1_value2, code2_value3, ..., code2_valueN); code3(code2_value1, code3_value2, code3_value3, ..., code3_valueN); . . . codeN(codeN_value1, codeN_value2, codeN_value3, ..., codeN_valueN); The lists are huge say like there are 100 parent codes and each has about 250 values in them. There will not be duplicates within a code list. Doing it in java and the solution i could figure out is. Store the values of first set of code in as codeMap.put(codeValue, duplicateCount). The count initialized to 0. Then compare the rest of the values with this. If its in the map then increment the count otherwise append it to the map. The downfall of this is to get the duplicates. Another iteration needs to be performed on a very large list. An alternative is to maintain another hashmap for duplicates like duplicateCodeMap.put(codeValue, duplicateCount) and change the initial hashmap to codeMap.put(codeValue, codeValue). Speed is what is requirement. Hope one of you can help me with it.

    Read the article

  • Java and Jasper

    - by bhargava
    Hey Guys, I have integrated Jasper Reports on my netbeans platform and i am able to generate reports using the following code. Map<String, Object> params = new HashMap<String, Object>(); Connection conn = DriverManager.getConnection("databaseUrl", "userid","password"); JasperReport jasperReport = JasperCompileManager.compileReport(reportSource); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, conn); JasperExportManager.exportReportToHtmlFile(jasperPrint, reportDest); JasperViewer.viewReport(jasperPrint); This stuff works perfect. But not i am trying to integrate Jasper with GWT.I have my server as glass fish server. I am getting the Connection object using the followind code. public static Connection getConnection() { try { String JNDI = "JNDI name"; InitialContext initCtx = new InitialContext(); javax.sql.DataSource ds = (javax.sql.DataSource) initCtx.lookup(JNDI); Connection conn = (Connection) ds.getConnection(); return conn; } catch (Exception ex) { ex.printStackTrace(); } return null; } and then Map params = new HashMap(); JasperReport jasperReport = JasperCompileManager.compileReport(reportSource); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, getConnection()); JasperExportManager.exportReportToHtmlFile(jasperPrint, reportDest); JasperViewer.viewReport(jasperPrint); but i always get Error.I am implementing this on Server.I am having RPC calls to get this method to work when a button is clicked. Can you please help me how to work on this.(That is to integrate Jasper reports with GWT). I would highly appreciate any explanation with some code as i am just a beginner. Thanks

    Read the article

  • DWR and Spring Security - User is deauthenticated in few seconds

    - by Vojtech
    I am trying to implement user authentication via DWR as follows: public class PublicRemote { @Autowired @Qualifier("authenticationManager") private AuthenticationManager authenticationManager; public Map<String, Object> userLogin(String username, String password, boolean stay) { Map<String, Object> map = new HashMap<>(); UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password); try { Authentication authentication = authenticationManager.authenticate(authRequest); SecurityContextHolder.getContext().setAuthentication(authentication); map.put("success", "true"); } catch (Exception e) { map.put("success", "false"); } return map; } public Map<String, Object> getUserState() { Map<String, Object> map = new HashMap<>(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); boolean authenticated = authentication != null && authentication.isAuthenticated(); map.put("authenticated", authenticated); if (authenticated) { map.put("authorities", authentication.getAuthorities()); } return map; } } The authentication works correctly and by calling getUserState() I can see that the user is successfully logged in. The problem is that this state will stay only for few seconds. In probably 5 seconds, the getAuthentication() starts returning null. Is there some problem with session in DWR or is it some misconfiguration of Spring Security?

    Read the article

  • Are there any garanties in JLS about order of execution static initialization blocks?

    - by Roman
    I wonder if it's reliable to use a construction like: private static final Map<String, String> engMessages; private static final Map<String, String> rusMessages; static { engMessages = new HashMap<String, String> () {{ put ("msgname", "value"); }}; rusMessages = new HashMap<String, String> () {{ put ("msgname", "????????"); }}; } private static Map<String, String> msgSource; static { msgSource = engMessages; } public static String msg (String msgName) { return msgSource.get (msgName); } Is there a possibility that I'll get NullPointerException because msgSource initialization block will be executed before the block which initializes engMessages? (about why don't I do msgSource initialization at the end of upper init. block: just the matter of taste; I'll do so if the described construction is unreliable)

    Read the article

  • Large ListView containing images in Android

    - by Marco W.
    For various Android applications, I need large ListViews, i.e. such views with 100-300 entries. All entries must be loaded in bulk when the application is started, as some sorting and processing is necessary and the application cannot know which items to display first, otherwise. So far, I've been loading the images for all items in bulk as well, which are then saved in an ArrayList<CustomType> together with the rest of the data for each entry. But of course, this is not a good practice, as you're very likely to have an OutOfMemoryException then: The references to all images in the ArrayList prevent the garbage collector from working. So the best solution is, obviously, to load only the text data in bulk whereas the images are then loaded as needed, right? The Google Play application does this, for example: You can see that images are loaded as you scroll to them, i.e. they are probably loaded in the adapter's getView() method. But with Google Play, this is a different problem, anyway, as the images must be loaded from the Internet, which is not the case for me. My problem is not that loading the images takes too long, but storing them requires too much memory. So what should I do with the images? Load in getView(), when they are really needed? Would make scrolling sluggish. So calling an AsyncTask then? Or just a normal Thread? Parametrize it? I could save the images that are already loaded into a HashMap<String,Bitmap>, so that they don't need to be loaded again in getView(). But if this is done, you have the memory problem again: The HashMap stores references to all images, so in the end, you could have the OutOfMemoryException again. I know that there are already lots of questions here that discuss "Lazy loading" of images. But they mainly cover the problem of slow loading, not too much memory consumption.

    Read the article

  • Java data structure suggestion.

    - by techoverflow
    Hi folks, I am a newbie in this field so please excuse my silly mistakes :) So the issue I am facing is: On my webpage, I am displaying a table. For now my issue is concerned with three columns of the table. First is : Area Code Second is : Zone Code Third is: Value The relationship between these three is: 1 Area Code has 6 different Zone code's and all those 6 Zone codes have corresponding "Value" I need a data structer that would give me the flexibility to get a "Value" for a Zone code, which falls under a particular Area code. I have the same zone codes for all the Area codes: Zone codes are: 111, 222, 333, 444, 555, 666 After surfing your stackoverflow, I thought I can go with this structure: Map<Integer, Map<Integer, Double>> retailPrices = new HashMap<Integer, Map<Integer, Double>>(); Map<Integer, Double> codes = new HashMap<Integer, Double>(); where reatailPrices would hold an Area Code and a Map of Zone code as Key and "Value" as Value. but when I am trying to populate this through a SQL resultset, I am getting the following error: The method put(Integer, Map<Integer,Double>) in the type Map is not applicable for the arguments (Integer, Double) on line: `while(oResult.next()) retailPrices.put((new Integer(oResult.getString("AREA"))), (pegPlPrices.put(new Integer(oResult.getString("ZONE_CODE")), new Double(oResult.getString("VALUE"))))); }` please help me figure out this problem. Am I following the right approach?

    Read the article

  • How to implement a collection (list, map?) of complicated strings in Java?

    - by Alex Cheng
    Hi all. I'm new here. Problem -- I have something like the following entries, 1000 of them: args1=msg args2=flow args3=content args4=depth args6=within ==> args5=content args1=msg args2=flow args3=content args4=depth args6=within args7=distance ==> args5=content args1=msg args2=flow args3=content args6=within ==> args5=content args1=msg args2=flow args3=content args6=within args7=distance ==> args5=content args1=msg args2=flow args3=flow ==> args4=flowbits args1=msg args2=flow args3=flow args5=content ==> args4=flowbits args1=msg args2=flow args3=flow args6=depth ==> args4=flowbits args1=msg args2=flow args3=flow args6=depth ==> args5=content args1=msg args2=flow args4=depth ==> args3=content args1=msg args2=flow args4=depth args5=content ==> args3=content args1=msg args2=flow args4=depth args5=content args6=within ==> args3=content args1=msg args2=flow args4=depth args5=content args6=within args7=distance ==> args3=content I'm doing some sort of suggestion method. Say, args1=msg args2=flow args3=flow == args4=flowbits If the sentence contains msg, flow, and another flow, then I should return the suggestion of flowbits. How can I go around doing it? I know I should scan (whenever a character is pressed on the textarea) a list or array for a match and return the result, but, 1000 entries, how should I implement it? I'm thinking of HashMap, but can I do something like this? <"msg,flow,flow","flowbits" Also, in a sentence the arguments might not be in order, so assuming that it's flow,flow,msg then I can't match anything in the HashMap as the key is "msg,flow,flow". What should I do in this case? Please help. Thanks a million!

    Read the article

  • Recursive Enumeration in Java

    - by Harm De Weirdt
    Hello everyone. I still have a question about Enumerations. Here's a quick sketch of the situation. I have a class Backpack that has a Hashmap content with as keys a variable of type long, and as value an ArrayList with Items. I have to write an Enumeration that iterates over the content of a Backpack. But here's the catch: in a Backpack, there can also be another Backpack. And the Enumeration should also be able to iterate over the content of a backpack that is in the backpack. (I hope you can follow, I'm not really good at explaining..) Here is the code I have: public Enumeration<Object> getEnumeration() { return new Enumeration<Object>() { private int itemsDone = 0; //I make a new array with all the values of the HashMap, so I can use //them in nextElement() Collection<Long> keysCollection = getContent().keySet(); Long [] keys = keysCollection.toArray(new Long[keysCollection.size()]); public boolean hasMoreElements() { if(itemsDone < getContent().size()) { return true; }else { return false; } } public Object nextElement() { ArrayList<Item> temporaryList= getContent().get(keys[itemsDone]); for(int i = 0; i < temporaryList.size(); i++) { if(temporaryList.get(i) instanceof Backpack) { return temporaryList.get(i).getEnumeration(); }else { return getContent().get(keys[itemsDone++]); } } } }; Will this code work decently? It's just the "return temporaryList.get(i).getEnumeration();" I'm worried about. Will the users still be able to use just the hasMoreElemens() and nextElement() like he would normally do? Any help is appreciated, Harm De Weirdt

    Read the article

  • Java: Typecasting to Generics

    - by bguiz
    This method that uses method-level generics, that parses the values from a custom POJO, JXlistOfKeyValuePairs (which is exactly that). The only thing is that both the keys and values in JXlistOfKeyValuePairs are Strings. This method wants to taken in, in addition to the JXlistOfKeyValuePairs instance, a Class<T> that defines which data type to convert the values to (assume that only Boolean, Integer and Float are possible). It then outputs a HashMap with the specified type for the values in its entries. This is the code that I have got, and it is obviously broken. private <T extends Object> Map<String, T> fromListOfKeyValuePairs(JXlistOfKeyValuePairs jxval, Class<T> clasz) { Map<String, T> val = new HashMap<String, T>(); List<Entry> jxents = jxval.getEntry(); T value; String str; for (Entry jxent : jxents) { str = jxent.getValue(); value = null; if (clasz.isAssignableFrom(Boolean.class)) { value = (T)(Boolean.parseBoolean(str)); } else if (clasz.isAssignableFrom(Integer.class)) { value = (T)(Integer.parseInt(str)); } else if (clasz.isAssignableFrom(Float.class)) { value = (T)(Float.parseFloat(str)); } else { logger.warn("Unsupported value type encountered in key-value pairs, continuing anyway: " + clasz.getName()); } val.put(jxent.getKey(), value); } return val; } This is the bit that I want to solve: if (clasz.isAssignableFrom(Boolean.class)) { value = (T)(Boolean.parseBoolean(str)); } else if (clasz.isAssignableFrom(Integer.class)) { value = (T)(Integer.parseInt(str)); } I get: Inconvertible types required: T found: Boolean Also, if possible, I would like to be able to do this with more elegant code, avoiding Class#isAssignableFrom. Any suggestions? Sample method invocation: Map<String, Boolean> foo = fromListOfKeyValuePairs(bar, Boolean.class);

    Read the article

  • Do the 'up to date' guarantees provided by final field in Java's memory model extend to indirect ref

    - by mattbh
    The Java language spec defines semantics of final fields in section 17.5: The usage model for final fields is a simple one. Set the final fields for an object in that object's constructor. Do not write a reference to the object being constructed in a place where another thread can see it before the object's constructor is finished. If this is followed, then when the object is seen by another thread, that thread will always see the correctly constructed version of that object's final fields. It will also see versions of any object or array referenced by those final fields that are at least as up-to-date as the final fields are. My question is - does the 'up-to-date' guarantee extend to the contents of nested arrays, and nested objects? An example scenario: Thread A constructs a HashMap of ArrayLists, then assigns the HashMap to final field 'myFinal' in an instance of class 'MyClass' Thread B sees a (non-synchronized) reference to the MyClass instance and reads 'myFinal', and accesses and reads the contents of one of the ArrayLists In this scenario, are the members of the ArrayList as seen by Thread B guaranteed to be at least as up to date as they were when MyClass's constructor completed?

    Read the article

  • What are the hibernate annotations used to persist a Map with an enumerated type as a key?

    - by Jason Novak
    I am having trouble getting the right hibernate annotations to use on a Map with an enumerated class as a key. Here is a simplified (and extremely contrived) example. public class Thing { public String id; public Letter startLetter; public Map<Letter,Double> letterCounts = new HashMap<Letter, Double>(); } public enum Letter { A, B, C, D } Here are my current annotations on Thing @Entity public class Thing { @Id public String id; @Enumerated(EnumType.STRING) public Letter startLetter; @CollectionOfElements @JoinTable(name = "Thing_letterFrequencies", joinColumns = @JoinColumn(name = "thingId")) @MapKey(columns = @Column(name = "letter", nullable = false)) @Column(name = "count") public Map<Letter,Double> letterCounts = new HashMap<Letter, Double>(); } Hibernate generates the following DDL to create the tables for my MySql database create table Thing (id varchar(255) not null, startLetter varchar(255), primary key (id)) type=InnoDB; create table Thing_letterFrequencies (thingId varchar(255) not null, count double precision, letter tinyblob not null, primary key (thingId, letter)) type=InnoDB; Notice that hibernate tries to define letter (my map key) as a tinyblob, however it defines startLetter as a varchar(255) even though both are of the enumerated type Letter. When I try to create the tables I see the following error BLOB/TEXT column 'letter' used in key specification without a key length I googled this error and it appears that MySql has issues when you try to make a tinyblob column part of a primary key, which is what hibernate needs to do with the Thing_letterFrequencies table. So I would rather have letter mapped to a varchar(255) the way startLetter is. Unfortunately, I've been fussing with the MapKey annotation for a while now and haven't been able to make this work. I've also tried @MapKeyManyToMany(targetEntity=Product.class) without success. Can anyone tell me what are the correct annotations for my letterCounts map so that hibernate will treat the letterCounts map key the same way it does startLetter?

    Read the article

  • Suitable data structures for saving files in localStorage (HTML5) ?

    - by WmasterJ
    It is nice when there isn't a DB to maintain and users to authenticate. My professor has asked me to convert a recent research project of his that uses Bespin and calculates errors made by users in a code editor as part of his research. The goal is to convert from MySQL to using HTML5 localStorage completely. Doesn't seem so hard to do, even though digging in his code might take some time. Question: I need to store files and state (last placement of cursor and active file). I have already done so by implementing the recommendations in another stackoverflow thread. But would like your input considering how to structure the content to use. My current solution Hashmap like solution with javascript objects: files = {}; // later, saving files[fileName] = data; And then storing in localStorage using some recommendations localStorage.setObject("files", files); // Note that setObject(key, data) does not exist but is added // using Storage.prototype.setObject = function() {... Currently I'm also considering using some type of numeric id. So that names can be changed without any hassle renaming the key in the hashmap. What is your opinion on the way it is solved and would you do it any differently?

    Read the article

  • Quickest way to compare a buch of array or list of values.

    - by zapping
    Can you please let me know on the quickest and efficient way to compare a large set of values. Its like there are a list of parent codes(string) and each code has a series of child values(string). The child lists have to be compared with each other and find out duplicates and count how many times they repeat. code1(code1_value1, code1_value2, code3_value3, ..., code1_valueN); code2(code2_value1, code1_value2, code2_value3, ..., code2_valueN); code3(code2_value1, code3_value2, code3_value3, ..., code3_valueN); . . . codeN(codeN_value1, codeN_value2, codeN_value3, ..., codeN_valueN); The lists are huge say like there are 100 parent codes and each has about 250 values in them. There will not be duplicates within a code list. Doing it in java and the solution i could figure out is. Store the values of first set of code in as codeMap.put(codeValue, duplicateCount). The count initialized to 0. Then compare the rest of the values with this. If its in the map then increment the count otherwise append it to the map. The downfall of this is to get the duplicates. Another iteration needs to be performed on a very large list. An alternative is to maintain another hashmap for duplicates like duplicateCodeMap.put(codeValue, duplicateCount) and change the initial hashmap to codeMap.put(codeValue, codeValue). Speed is what is requirement. Hope one of you can help me with it.

    Read the article

  • how to add data in Table of Jasper Report using Java

    - by Areeb Gillani
    i am here to ask you just a simple question that i am trying to pass data to a jasper report using java but i dont know how to to, because the table data is very dynamic thats y cannot pass sql query. any idea for this. i have a 2D array of object type, where i have all the data... so how can i pass that... Thanx in advance...!:) ConnectionManager con = new ConnectionManager(); con.establishConnection(); String fileName = "Pmc_Bill.jrxml"; String outFileName = "OutputReport.pdf"; HashMap params = new HashMap(); params.put("PName", pname); params.put("PSerial", psrl); params.put("PGender",pgen); params.put("PPhone",pph); params.put("PAge",page); params.put("PRefer",pref); params.put("PDateR",dateNow); try { JasperReport jasperReport = JasperCompileManager.compileReport(fileName); if(jasperReport != null ) System.out.println("so far so good "); // Fill the report using an empty data source JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, new JRTableModelDataSource(tbl.getModel()));//con.connection); try{ JasperExportManager.exportReportToPdfFile(jasperPrint, outFileName); System.out.printf("File exported sucessfully"); }catch(Exception e){ e.printStackTrace(); } JasperViewer.viewReport(jasperPrint); } catch (JRException e) { JOptionPane.showMessageDialog(null, e); e.printStackTrace(); System.exit(1); }

    Read the article

  • Looking for an appropriate design pattern

    - by user1066015
    I have a game that tracks user stats after every match, such as how far they travelled, how many times they attacked, how far they fell, etc, and my current implementations looks somewhat as follows (simplified version): Class Player{ int id; public Player(){ int id = Math.random()*100000; PlayerData.players.put(id,new PlayerData()); } public void jump(){ //Logic to make the user jump //... //call the playerManager PlayerManager.jump(this); } public void attack(Player target){ //logic to attack the player //... //call the player manager PlayerManager.attack(this,target); } } Class PlayerData{ public static HashMap<int, PlayerData> players = new HashMap<int,PlayerData>(); int id; int timesJumped; int timesAttacked; } public void incrementJumped(){ timesJumped++; } public void incrementAttacked(){ timesAttacked++; } } Class PlayerManager{ public static void jump(Player player){ players.get(player.getId()).incrementJumped(); } public void incrementAttacked(Player player, Player target){ players.get(player.getId()).incrementAttacked(); } } So I have a PlayerData class which holds all of the statistics, and brings it out of the player class because it isn't part of the player logic. Then I have PlayerManager, which would be on the server, and that controls the interactions between players (a lot of the logic that does that is excluded so I could keep this simple). I put the calls to the PlayerData class in the Manager class because sometimes you have to do certain checks between players, for instance if the attack actually hits, then you increment "attackHits". The main problem (in my opinion, correct me if I'm wrong) is that this is not very extensible. I will have to touch the PlayerData class if I want to keep track of a new stat, by adding methods and fields, and then I have to potentially add more methods to my PlayerManager, so it isn't very modulized. If there is an improvement to this that you would recommend, I would be very appreciative. Thanks.

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >