text
stringlengths
46
37.3k
title
stringlengths
12
162
Java : This is the second time I found myself writing this kind of code , and decided that there must be a more readable way to accomplish this : My code tries to figure something out , that 's not exactly well defined , or there are many ways to accomplish it . I want my code to try out several ways to figure it out ,...
Letting the code try different things until it succeeds , neatly
Java : I was playing around with generics and found that , to my surprise , the following code compiles : I would expect T to be inferred to B . A does not extend B . So why does n't the compiler complain about it ? T seems to be inferred to Object , since I can pass a Generic < Object > as well.Moreover , when actuall...
Why is n't java typesafe when inferring array types ?
Java : For my flow chart I generate three different agents via different sources . Now I want to handle them differently in diverse blocks in the flow chart . For instance , I want to have a different delay time for the agents . Since I am new to AnyLogic and not that good with Java , I have problems to understand how ...
How can I handle different materials in one flowchart in Anylogic ?
Java : I ran into some strange behaviour of Java generics today . The following code compiles fine and works as you would expect : but if you change the type of the variable generic to GenericClass ( note no type parameters ) compilation fails with the message `` incompatible types : java.lang.Object can not be convert...
Strange generics behaviour . Being erased early ?
Java : Using vaadin ( 7.7.3 ) I 'm filtering a grid by name , this filtering takes a couple seconds to remove the objects from the Grid gui . And so , if I click on that timelapse a row of the Grid which is removed from the Container , it raises an exception : I guess this is normal because it removes the objects from ...
How to catch an exception when filtering a vaadin grid
Java : My original question used FileNotFoundException and IllegalStateException and therefore they are included in the answer . I have changed them to their superclasses IOException and RuntimeException respectively for simplicity.This compiles ( not using ternary , 1 checked , 1 unchecked ) : This also compiles ( usi...
Using Ternary Operator to Throw Checked or Unchecked Exceptions
Java : I used to think was a reliable way to determine whether the shell that launched my Java application was interactive or not . This allowed me to use ANSI escape sequences in interactive mode and plain System.out/System.err whenever the program 's output was redirected to a file or piped to the stdin of some other...
Determining whether a Java program has been launched from an interactive shell
Java : In some old Java code , I found a class that contains a lot of methods that all use the same error handling code ( try-catch with a lot of error handling , logging and so on ) . It looks like the first method was simply copied and then the code in the try block was slightly adapted . Here is what it basically lo...
How to simplify a class with lot 's of copy-pasted error handling code ?
Java : As per the documentation on Oracle 's website : Side-effects in behavioral parameters to stream operations are , in general , discouraged , as they can often lead to unwitting violations of the statelessness requirement , as well as other thread-safety hazards . Does this include saving elements of the stream to...
Saving to database in stream pipeline
Java : The polynomial 's degree should be # of points - 1 e.g . if there are 2 points given it should be a line.I know I can solve this using a matrix e.g . if there are 4 points : the polynomial would be y = ax^3 + bx^2 + cx + d and the matrix would beand I can solve for a , b , c , d . Is there a library that can do ...
Java library for estimating a polynomial based on a set of points
Java : I 'm having some trouble trying to read a String and a Double from a txt file . Here is my txt file : And here is the code I am using to read them : Whenever I run this code , Exception in thread `` main '' java.util.InputMismatchException appears telling me the problem is in nextDouble ( ) .Does anybody know ho...
Need to read String and Double from file
Java : A customer is complaining that he 's experiencing a memory leak in our Java application.Despite all my efforts to reproduce his environment , configuration and usage , I was n't able to reproduce , and thus identify , the leak.I 'd want to go down another path ... Instead of trying to replicate it , maybe I coul...
Remotely identify a memory leak in an application used by a customer
Java : I have this codeand it works . But when I flip the order , I get an illegal forward reference error . I 'm a little bit shocked , I did n't expect something like this from Java . : ) What happens here ? Why is the order of declarations important ? Why does the assignment work but not the method call ? <code> pri...
Why is the order of declarations important for static initializers ?
Java : I want to use JavaPoet to generate an annotation with a type literal as value . For example : I 've tried all the options I can think of , but none work : using $ L generates interface MyServiceusing $ T generates my.package.MyService , which is close but misses the .class part.using $ N gives an error : expecte...
How do I get JavaPoet to generate a class literal ?
Java : I am trying to get current time in other time zone . I used this code for this : But , when I am running this code , this code provides the current time in CET as the time in my local machine is in CET.I am confused . Then why there is scope to provide a TimeZone in constructor ? <code> GregorianCalendar calende...
GregorianCalendar Class in Java
Java : Out of the two methods in StringBuilder 's append , which of the following code is better ? or <code> stringBuilder.append ( '\n ' ) ; stringBuilder.append ( `` \n '' ) ;
Which one is better to pass to StringBuilder.append ?
Java : If I have a class that implements two interfaces and I send that class to an overloaded method that accepts either interface ; which variant of the method will be called ? In other words , if I have something like this : And I send my class C to the method/s in D : Which method should be called ? Does the Java s...
Multiple interfaces in a java class - which gets used for method calls ?
Java : Why does it seem that Gson ignores the nested generic type declaration when serializing ? I am trying to get Gson to use the compile-time type I specify , instead of the runtime type of objects in the list . I am also using an abstract superclass for A.java , but the example below has the same problem.Output : E...
Why does Gson serializes runtime type in list , not specified compile-time type ?
Java : I have used SLF4J logging to print all the logs . I am using the latest version of org.slf4j . implementation 'org.slf4j : slf4j-api:2.0.0-alpha1 ' implementation 'org.slf4j : log4j-over-slf4j:2.0.0-alpha1'But I 'm getting the following error and also no logs are being printed.The logs are working fine with the ...
How to enable logging in org.slf4j for the version : ' 2.0.0-alpha1 ' in Spring boot
Java : I have an android application which is getting gesture coordinates ( 3 axis - x , y , z ) . I need to compare them with coordinates which I have in my DB and determine whether they are the same or not.I also need to add some tolerance , since accelerometer ( device which captures gestures ) is very sensitive . I...
Compare graph values or structure
Java : The code below succeeds in Java 8 but throws a ClassCastException in Java 11 . Why did the behavior change ? I could not find any related changes in OpenJDK 's Java 9 , Java 10 or Java 11 feature sets . <code> public class GenericsExample { public static void main ( String [ ] args ) { Set < Car > set = new Hash...
Why does this code with generics throw a ClassCastException in Java 11 ?
Java : The question : while this function has been called from a thread , IS there a way the list passed to this function can be modified by another thread ? <code> Integer getElement ( List < Integer > list ) { int i = Random.getInt ( list.size ( ) ) ; return list.get ( i ) ; }
Can a list passed to a function be modofied by another thread in Java ?
Java : I am working with Java 8 streams , and would like to come up with a way to debug them . So i thought I could write a filter that printed out the elements at a stage of the stream , something like this : Close , but that 's not quite it , as it does n't have the proper delimiters to make it legible : What I want ...
Tracing Streams
Java : I 'm working on an app for a robot where the user can define punch combinations which the robot will later fetch from the device . To allow the user to store these trainings I have defined a class `` Trainings '' which holds the id , the name and the punch combination of the training . This training is later sav...
Nullpointer Exception after deleting entry from SQL database
Java : I just learned from Peter Lawreys post that this is valid expression , and evaluates to true.My question is , why is it allowed to have double literals which ca n't be represented in a double , while integer literals that ca n't be represented are disallowed . What is the rationale for this decision.A side note ...
Why is arbitrary precision in double literals allowed in Java ?
Java : The code : is used by my class : As you see it has two type parameters P and X . Despite of that the X can always be deduced from P but the language requires me to supply both : Is there any trick to get rid of the X type parameter ? I want just useAlso , I do n't want lose type information and use it as : <code...
Eliminate type parameter of java generics
Java : Input string is `` 1.01 '' and output is `` . '' . I ca n't understand why matcher.find ( ) returns true , there are no symbols like `` + '' , `` - '' , `` * '' , `` ^ '' , `` % '' in input string . Why did it happen ? <code> String s = `` 1.01 '' ; Matcher matcher = Pattern.compile ( `` [ +-/\\*\\^\\ % ] '' ) ....
what is wrong with matcher.find ( ) ?
Java : Consider the following code : I came across this the other day when accidentally calling a static method in a non-static way.I know that you should n't call static methods in a non-static way , but I am still wondering , why is n't it possible to infer the type in this case ? <code> class Test { void accept ( Co...
Java 8 type inference with non-static access of static members
Java : Since this question is back to four votes to close , I 'm trying again to ask a more narrow question that hopefully the community will view more favorably.Which specific design decisions in Java are documented to be done the way that they are not because that was the preferred design decision , but rather becaus...
What Java designs are explicitly done to support backwards compatability ?
Java : I have a CreateOrder instance which has some String , Integer and Double states in it . When I create an object for CreateOrder in my JUnit test and send it over , I am able to validate String attributes but not Integer using Optional API as follows - Like for aoid , I also want to user ofNullable ( ) for intege...
Validating inputs using Optional
Java : I found a scenario where java program behaves differently after renaming a variable . I understand this is n't actually code that anyone would use but if someone knows whats going on it would be nice to have an explanation . I tried this with java 1.6 on Eclipse Kepler.This outputs : hello Exception in thread ``...
Java changing variable name changes program behaviour
Java : I 've read pretty often , that using try-catch is quite slow compared to normal code.Now I wonder if the number of caught exceptions affects the performance of the code or not.So isslower than ? Of course I 'm only referring to the code in the try-clause and if no exception is caught . <code> try { ... } catch (...
Does the number of caught exceptions affect the performance of the try-code ?
Java : Coursework brief requires me to assign an optional cmd argument to a static final variable.I have tried doing it in main ( ) but compiler complains `` can not assign a value to final variable '' . I 've tried doing it in a static method called by main ( ) but same error . I 've heard about static blocks being us...
How to initialize static final variables based on cmd args ?
Java : I am trying to call into a Rust library from Java and I really want to use SWIG to generate the interface layer from a C header file that I write ( I also want to allow regular C clients to call into my library , hence I think it makes sense to maintain one interface header ) .I am doing this all on Windows usin...
Is it possible to use Java , SWIG and Rust together ?
Java : Consider the abstract Data class with an abstract Builder : The class is extended , which also includes its own extended Builder : The Extension object gets all methods from both classes . However the order the setter methods is called is important . This is OK : Whereas this produces a compilation error : I kno...
How do I define a builder pattern hierarchy where the setters can be called in any order
Java : I 've been experimenting with the HttpClient stuff in the Java 9/10 incubator , and have the following trivial code ( virtually stolen from the project home page ! ) : I find it works fine if it 's pointed at a URL that is not the localhost , but fails if I ask for the localhost ( whether by the name `` localhos...
java 10 httpclient incubator GET request fails on node.js server
Java : I 'm building ( well , trying to build ) a simple usenet news reader . The code below works . Is grabs the username , host , password from the SharedPreferences and connects to the server and sucessfully authenticates , however it locks up the UI until all the tasks are done.How would i change this code so that ...
Connect to a Socket locks up UI
Java : So here it is this exampleand class Stuff is defined as followThe output isHow does Java tell the null is a String ? If I change Stuff to I get compilation error for Stuff ( null ) : Again , why does Java `` decide '' null is a String ? <code> public static void main ( String [ ] args ) { new Stuff ( null ) ; ne...
What is the type on null as a method argument ?
Java : I would like to do the following : That is , given an immutable list of T , you can add any U to the list to yield an immutable list of U , with the constraint that U must be a supertype of T. For exampleI can add a monkey to a list of monkeys , yielding a new list of monkeys ; I can add a human to a list of mon...
Substitute for illegal lower bounds on a generic Java method ?
Java : I want to create two interfaces with inverse relationships . I 'm not sure if expression C extends Category < D , Item < D , C > > is correct , but at least there are no compiler errors.I extends Item gives the warning Item is a raw type . References to Item < D , C > should be parametrized . I triedbut this res...
Generic Interface with inverse relationship
Java : I have a requirement to trigger the Cloud Dataflow pipeline from Cloud Functions . But the Cloud function must be written in Java . So the Trigger for Cloud Function is Google Cloud Storage 's Finalise/Create Event , i.e. , when a file is uploaded in a GCS bucket , the Cloud Function must trigger the Cloud dataf...
How to trigger Cloud Dataflow pipeline job from Cloud Function in Java ?
Java : I 've been trying to figure out what the best practice is for form submission with spring and what the minimum boilerplate is to achieve that . I think of the following as best practise traitsValidation enabled and form values preserved on validation failureDisable form re-submission F5 ( i.e . use redirects ) P...
Spring form submission with minum boilerplate
Java : I am trying to create a huffman tree , and am in the middle of attempting to merge two trees . I can not figure out how to remove a Tree in my program without getting the `` concurrent Modification Exception '' because I am iterating over a list and attempting to remove from the list at the same time . <code> Bi...
How to delete from a list , while modifying the list
Java : I am trying to take a part of a String from point ( a , b ) and replace letters from given values in the string into ' X's.Example : If the string is ABC123 and switch ( 3,5 ) is called , it would change it to ABCXXX.So far I have : I am very lost ... .thanks for any help ! <code> public void switch ( int p1 , i...
Java Changing Part of String with Specific Character
Java : Can somebody who understand the Java Memory Model better than me confirm my understanding that the following code is correctly synchronized ? I understand that this code is correct but I have n't worked through the whole happens-before math . I did find two informal quotations that suggest this is lawful , thoug...
Java Memory Model : Is it safe to create a cyclical reference graph of final instance fields , all assigned within the same thread ?
Java : I have a string ; How can I split/extract logical values from this string inside parenthesis as ; Any idea ? all is welcome <code> String value = `` ( 5+5 ) + ( ( 5+8 + ( 85*4 ) ) +524 ) '' ; ( 85*4 ) as one ( 5+8 + one ) as two ( two+524 ) as three ( ( 5+5 ) + three ) as four ...
Extract from string in Java
Java : The Java project I 'm working on uses a combination of code analysis tools : PMD , Checkstyle and FindBugs . These pick up on plenty of bugs , style issues etc . but one often slips through the net : Note the other way round is checked , i.e . public abstract BadlyNamedClass gives PMD warning `` Abstract classes...
Is there a Checkstyle/PMD rule `` Non-abstract classes should not be named AbstractXXX '' ?
Java : I have currently two queues and items traveling between them . Initially , an item gets put into firstQueue , then one of three dedicated thread moves it to secondQueue and finally another dedicated thread removes it . These moves obviously include some processing . I need to be able to get the status of any ite...
Tracking the progress between Queues in a Map
Java : I have a constructor which gets a HashSet and a HashMap . I need to run a validation check on one hashMAp and combine it with the hashSet , as 'super ' must receive only one hashSet.I ca n't find a way to do it as I get following error : can not reference this before supertype constructorExample : I want to do s...
How to run a function before calling super in java ?
Java : I have TypeToken class used to represent some generic type like this : TypeToken < List < String > > listOfStrings = new TypeToken < List < String > > { } And this works fine , TypeToken is just class TypeToken < T > { } with simple method to get that type . Now I wanted to create simple methods for common type ...
Unexpected generic behavior with TypeToken nesting generic types
Java : If I run my project in Eclipse all is OK . But when I do : and afterwards start my project then it is not working . I found this difference : Eclipse : mvn package : Why ? What could I do , that mvn package loads the same jetty version 9.2.13 ? UPDATE : I found some additional differences : Compiling in Eclipse ...
mvn package load other Library as Eclipse
Java : When an exception occurs during the handling of an exception , only the last exception gets reported , because I can add just one exception to an Error object . How to report all exception in the final error message ? Example : In the example everything fails . The database insert causes ex1 . The rollback cause...
How to avoid exception shadowing ?
Java : I am preparing for the OCA SE 7 exam , and some of these questions are really ( ! ) tricky.In one of the books Im using I found an error I think , so I would like to confirm the following please ... After the println method executes , how many String objects are there in the pool ? It is my understanding that : ...
String count in the pool with println
Java : Assume this code : Here , a temporary object new Foo ( ) creates a statically held Thread thread which utilizes an instance-tied String thing in an anonymous implementation of Runnable . Does the String thing get garbage collected after expiration of new Foo ( ) , or will it persist for its use within run ( ) ? ...
Will an unreferenced object used in an anonymous class instance not expire ?
Java : Scenario : I want to have an enum containing all the playing cards in a standard deck . For this example ignore the jokers.Writingfeels wrong.I 'd like to be able to do something like thisI 've considered defining card as a class containing suit and face fields , where suit and face are themselves enums . Howeve...
Enumerate enum-instances with loop
Java : I 'm new to Netty . There is a problem about file transfer confusing me for days . I want to send image file from client to server.The code below is executable . But only I shutdown server forcibly can I open received image file normally . Otherwise , it shows `` It looks like you do n't have permission to view ...
How can I know if there is no data to read in Netty ByteBuf ?
Java : Java requires the instantiation of a bounded type parameter to its upper bound class to have a cast , for example : T is already restricted to Integer or one of its sub classes ( I know , there are n't any ) upon declaration , and it seems to me that any bounded type parameter may only be instantiated to its upp...
Why does java require a cast for the instantiation of a bounded type parameter to its upper bound class ?
Java : Bridge methods are used in java to handle covariance in derived methods , and to change visibility on derived methods.However , both of these cases are for instance methods ( as you ca n't derive static methods ) .I was looking at how Kotlin generates argument defaults , and I was struck that it uses static brid...
Does javac ever generate static bridge methods ?
Java : I have something like the below : A collection of say 100 , where the stackid could be duplicate with different questionIds . Its a one to many relationship between stackId and questionIdIs there a streamy , java 8 way to convert to the below strcuture : Which would be a collection of 25 , with each instance hav...
grouping objects java 8
Java : Actually , this is the first time I see a code like this : two lines I do n't understand : <code> class A { public static void main ( String args [ ] ) { outer : for ( int i=0 ; i < 10 ; i++ ) { for ( int j=0 ; j < 10 ; j++ ) { if ( j > i ) { System.out.println ( ) ; continue outer ; } System.out.print ( `` `` +...
I need a help to understand this code
Java : Hello I was trying to use Java regular expression to get the required context path from the following path information.I want to write regular expression to get `` /Systems '' and `` /lenovo '' separately.I tried the following regular expression using groups but not working as expected.Could any body tell me wha...
Regular Expression for Separating Paths
Java : I am wondering if there is a way to combine multiple attributes from an object into a list of String . In My Case , I have an object with the name `` debitCardVO '' and I want it to convert from object to ListHere is my code Snippet : <code> for ( DebitCardVO debitCardVO : debitCardVOList ) { List < String > deb...
How to convert multiple attributes of object into List < String > using java 8
Java : Found fact about unbounded wildcards that is annoying me . For example : It fails , although works with Map < ? , ? > or Map < ? , Map < Integer , String > > return type.Could someone tell me the exact reason ? Thanks in advance.UpdateSeems that i understood and the simplest explanation for this question ( omitt...
Nested wildcards
Java : The Dagger 2 documentation suggests providing different configurations for testing and production using an interface for ProductionComponent and TestComponent , as follows : Let 's say we have an Android activity ( MyApp ) which uses ProductionComponent : Generally , what 's the best way to use DaggerTestCompone...
Testing with Dagger 2 using separate component configurations in Android
Java : I have a series of points , which represent mobile devices within a room . Previously I have systematically emitted a ping from each and recorded the time at which it arrives at the others to calculate the distances.Here 's a simple diagram of an example network.The bottom A node should have been a D insteadAfte...
Positioning Devices ( Intersecting Circles )
Java : While refactoring some code I stumbled over this oddity . It seems to be impossible to control the strictfp property for an initializer without affecting the entire class . Example : From the JLS , Section 8.1.1.3 I gather that the initializer would be strictfp if the class would be declared using the strictfp m...
How to make a ( static ) initializer block strictfp ?
Java : When user change Display settings scaling ( Windows 10 , right click on desktop , select Display settings and scale to 150 % ) , suddenly all values reported by or orbecome invalid . Is there a way how to get the actual values ? <code> GraphicsDevice device = MouseInfo.getPointerInfo ( ) .getDevice ( ) ; Rectang...
obtain Windows 10 Display settings values in Java
Java : I am trying to create an app that will redirect to a certain webpage when run . I would like this app to be full screen with no title bar or browse bar . I am able to call a BrowseSession to bring up the proper website in the browser but it does n't give me the desired feel . Here is the code I am using for the ...
How to suppress the browser top bar while using a BlackBerry BrowserSession
Java : I have a question about g1gc.These are the heap usage graph.The above is -Xms4g -Xmx4g.The bottom is -Xms8g -Xmx8g.I do n't know why the 8g option causes g1gc to happen more often . Other options are all default.And server spec is 40 logical process . ps . What are the proper tuning options ? addtional questionC...
Why do I get GC more often when I raise memory ?
Java : Recently I was playing around with some simple Java code using main methods to quickly test the code I wrote . I ended up in a situation where I had two classes similar to those : I was quite surprised that the code stopped compiling and Eclipse complained that Exception IOException is not compatible with throws...
Signature difference when hiding static method in a subclass
Java : I saw a similar code in google guava ( as factory methods ) for making instances of Hashmap without mentioning the generic types.I do n't understand how the generic is getting inferred by the above program.I mean how can the function getHashMap understand the type of map since i 'm not passing any type informati...
How is the generic type getting inferred here ?
Java : I 'm trying to get a head start on practicing interview questions and I came across this one : Turn String aaaabbbbddd into a4b4d3You would basically want to convert the existing string into a string with each unique character occurrence and the number of times the character occurs . This is my solution but I th...
Turn String aaaabbbbddd into a4b4d3
Java : I have a simple xml file and I want to remove everything before the first < item > tag . The following java code is not working : What is the correct way to do this ? And how do I address the non-greedy issue ? Sorry I 'm a C # programmer . <code> < sometag > < something > ... .. < /something > < item > item1 < ...
Simple java regular expression replace question
Java : I 'm trying to create a work queue class ( FooQueue ) that has : a set of function members doing work ( do* ) . Each one of them take one parameter , having the same type ( FooItem ) .an 'add ' function that takes 2 parameters : one of the above functions , and a FooItem . Most importantly , the add function sho...
passing and enforcing a member function in java
Java : When I 'm looking at Spring FrameWork 3.0 I see the following code example : This option does n't work for me . Only when I change the code the following way : It works fine . Can anybody tell me why ? <code> @ RequestMapping ( `` /index.dlp '' ) public ModelAndView index ( ) { logger.info ( `` Return View '' ) ...
Spring MVC framework very basic Dispatcher question
Java : I 've just been profiling some code where I increment some frequency counters with the following code : The creation of the query takes almost 50 % of the execution time , and I 'd like to reuse the work somehow . Is it safe to save the query and ops objects in a ThreadLocal and just call query.field ( `` text '...
Is there a good pattern for reusing Morphia queries ?
Java : I am designing the API for a service that deals with Job entities . I need to retrieve jobs given a status . So , I ended up naming my methods like so : A while later I realised that I also need to be able to retrieve jobs which do n't belong to a given status . Say , I want to retrieve all but the closed jobs.I...
How should I name this method ?
Java : I just started working in Java networking protocols . I am trying to connect to the internet using my proxy server . When I see the post at 'https : //www.tutorialspoint.com/javaexamples/net_poxy.htm ' , they set the http.proxyHost property to 'proxy.mycompany1.local ' . I know I can set this to my proxy server ...
what is 'proxy.mycompany1.local '
Java : If I have this interface : Why ca n't I implement it like this ? It seems like void should be covariant with everything . Am I missing something ? Edit : I should have been clearer that I 'm looking for the design justification , not the technical reason that it wo n't compile . Are there negative consequences t...
Why is void not covariant in Java ?
Java : I 've been working on some ways to optimize LinkedList 's . Does anyone know if the Java default doubly-linked LinkedList class is optimized to do get ( ) operations in reverse ? For example : Would the call to list.get ( half + 1 ) optimize the search and go in reverse since it is a doubly-linked list ? It woul...
Is Java 's LinkedList optimized to do get ( index ) in reverse when necessary ?
Java : Possible Duplicate : Java import confusion When i read play frameworks documentation , I found this.In the first line itself they have imported all the classes under play package . Then what is the use of second line . Check this link . Go to 'Providing an application error page ' section.Correct me if i 'm wron...
Why some Java codes imports same package again ?
Java : This question has received a total of several paragraphs of answer . Here is the only sentence that actually tells me what I was looking for : Your examples would make little difference since intermediate computations need to be stored temporarily on the stack so they can be used later on.In fact , it answers my...
Does adding local variables to methods make them slower ?
Java : I was asked to implement an `` access policy '' to limit the amount of concurrent executions of a certaing process within an application ( NOT a web application ) which has direct connection to the database.The application is running in several machines , and if more than a user tries to call the process , only ...
Limit concurrent execution of an application process using database
Java : Occasionally , I meet an interesting , strange thing : same block of encrypted text can be decrypted using several different key ! Can anyone please indicate me what 's going wrong ? Thanks a lot.Please do n't try to let me switch to triple DES/AES etc , I just want to know where the problem is - the way calling...
Strange DES behavior - decryption is successful using different keys
Java : I 'm working on a legacy Java application , that deals with `` fruits '' and `` vegetables '' , let 's say , for the sake of the question.They are treated as different things internally , cause they do n't have all methods/properties in common , but a lot of things are DONE very similar to both of them.So , we h...
What is the proper design to deal with this ?
Java : I try to find the greatest common divisor for two integers . But I do n't understand what is wrong with my code : <code> public class Main { public static void main ( String [ ] args ) { Scanner s = new Scanner ( System.in ) ; int a = s.nextInt ( ) ; int b = s.nextInt ( ) ; while ( a ! = 0 | b ! = 0 ) { if ( a >...
Greatest common divisor
Java : i am basically coming from java background and struggling to understand the modulo operation in Ruby . The above operation in Java yields , 2 -2 2 -2But in Ruby , the same expression yields 21-1-2 .How logically ruby is good at this ? How the module operation is implemented in Ruby ? If the same operation is def...
Why ruby modulo is different from java/other lang ?
Java : This works ok : This does not compile : Error message : Why ? <code> Map aMap ; aMap = new HashMap < String , TreeSet < String > > ( ) ; Map < String , Set < String > > aMap ; aMap = new HashMap < String , TreeSet < String > > ( ) ; Compilation failed ( 26/05/2014 11:45:43 ) Error : line 2 - incompatible types -...
HashMap / TreeSet combination inconsistency
Java : I try to learn about good practices in programming and I 'm stuck with this question . I know that in Java , recursive functions can be ' a pain in the ass ' ( sometimes ) , and I try to implement as much as I can the tail version of that function . Is it worth bothering with this or should I do in the old fashi...
When using Java/Kotlin for programming is recommended to use Tail recursion or the Iterative version ? Is there any difference in performance ?
Java : I created a class MyList that has a fieldI would like to be able to iterate the list like this : ( when my list is an instance of MyList ) .How ? What should I add to my class ? <code> private LinkedList < User > list ; for ( User user : myList ) { //do something with user }
How do I iterate a class of my creation in Java ?
Java : Is there any difference performance-wise between the two code snippets below ? andFor me , I think the second one is better , but it is longer . The first one is shorter , but I am not really sure if it is faster . I am not sure , but to me it seems like every time that loop is iterated , auth.getProjects is cal...
Is there any difference between these two loops ?
Java : A common pattern with a map is to check if a key exists and then act on the value only if it does , consider : However this is generally considered poor , as it requires two map lookups , where this alternative only requires one : Yet this second implementation has it 's own problems . In addition to being less ...
Why do n't common Map implementations cache the result of Map.containsKey ( ) for Map.get ( )
Java : can anybody explain this why its happeningit prints zero . <code> int i=0 ; i=i++ ; i=i++ ; i=i++ ; System.out.println ( i ) ;
unable to make out this assignment in java
Java : I have a classI also have another classThe Log class works perfectly fine , I use it all the time . Now when I do this : I get the compiler error The method d ( String , Object ... ) in the type Log is not applicable for the arguments ( Configuration ) . I can solve this : My problem : How is this different ? In...
toString : When is it used ?
Java : I 'm trying to dynamically load a Groovy script as a class but the class object is created even when the script 's code does not compile.For example , a simplified version of my Groovy code to load the Groovy script is as follows : Clearly , the code blah blah blah is n't a legitimate Groovy script . And yet , a...
GroovyClassLoader call to parseClass is successful , even when code does not compile
Java : I have producer and consumer connected with BlockingQueue.Consumer wait records from queue and process it : I need pause this process for a while from other thread . How to implement it ? Now I think implement it such , but it 's looks like bad solution : <code> Record r = mQueue.take ( ) ; process ( r ) ; priva...
Suspend consumer in producer/consumer pattern
Java : example code : Question : will the literal string `` hi '' somehow stay in memory , even after the StringBuffer has been garbage collected ? Or is it just used to create a char array for the StringBuffer and then never put anywhere in memory ? <code> StringBuffer sb = new StringBuffer ( `` hi '' ) ; sb = null ;
StringBuilder / StringBuffer with literal string in memory
Java : Some background : I created a contrived example to demonstrate use of VisualVM to my team . In particular , one method had an unnecessary synchronized keyword , and we saw threads in the thread pool blocking , where they did n't need to be . But removing that keyword had the surprising effect described below , a...
Why does this code run faster with a lock ?
Java : I am trying to change the default font in my app . But its not working . These are steps I have taken:1 ) Created class TypefaceUtil.java2 ) In a class extending Application:3 ) In styles.xmlStill its not working . Am I missing something ? <code> import android.content.Context ; import android.graphics.Typeface ...
Unable to change default font in Android app
Java : I 'm missing some kind of collection functionality for a specific problem.I 'd like to start with a few informations about the problem 's background - maybe there 's a more elegant way to solve it , which does n't end in the specific problem I 'm stuck with : I 'm modelling a volume mesh made of tetrahedral cell...
Java : efficient Collection concept for a paired objects