lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Java
I want to select the first row in a table , order by time ( ascending ) , then delete that row . I do n't want to use two queries since there 's a possibility that another client could select that row before it gets deleted ( there will be several machines connected at once from different networks ) .I was thinking I c...
SELECT * FROM ` mytable ` ORDER BY ` time ` LIMIT 1 ; DELETE FROM ` mytable ` ORDER BY ` time ` LIMIT 1
SELECT and DELETE
Java
Hi I have a question regarding a log4j logger.There is a part of the logger text I do n't quite follow.The line looks as followsI had a look but I ca n't seem to find this as a regular expression , it smells strongly like it could be though and I suspect that it will be replaced by the returned value of someObject.func...
logger.debug ( `` Some text goes here [ { } ] and some more text here '' , someObject.function ( ) ) ;
log4j regular expression ? [ { } ]
Java
Id like to improove continuous delivery . I am using a Tomcat 8 and maven.I use mvn tomcat : redeploy to deploy the webapp.In tomcat documentation I found this part : Deploy A New Application Archive ( WAR ) RemotelyIf installation and startup is successful , you will receive ( ... ) Otherwise , the response will start...
@ Servicepublic class AvoidStartupOnMissingDatabase implements SmartInitializingSingleton { @ Override public void afterSingletonsInstantiated ( ) { throw new RuntimeException ( `` Do not deploy this app ! `` ) ; } } java.lang.RuntimeException : Do not deploy this app ! at xxx.AvoidStartupOnMissingDatabase.afterSinglet...
Optimize continuous deployment ( cancel throu chain-of-responsibility )
Java
I have a rather central class responsible for some Utility methods . I wanted to provide an additional overload for a method which was declared as follows : Now since I do n't really like Rawtypes , I specified the collections out into the least common denominator I can expect : So far so good , this got rid of the raw...
public static void removeDuplicated ( Collection fullList , Collection itemsToRemove ) { //implementation stripped for brevity } public static void removeDuplicated ( Collection < Map < ? , ? > > fullList , Collection < Map < ? , ? > > itemsToRemove ) { } public static < T extends TeObjectWrapper > void removeDuplicate...
Erasing Collections generics and conflicting overloads
Java
We currently use Beyond Compare 3.0 and I am quite pleased with it . However , it would be great if I could easily specify an exclusion for a specific one-time case . This is needed when I am doing a code review of some refactoring . For instance : Old codeNew code : In this case , I have hundreds of changes that I am ...
doSomething ( ConstantsInterface.FOOBAR ) ; doSomething ( BetterEnumeration.FOOBAR ) ;
Is there a file diff tool that allows for exceptions ?
Java
I have integrated some HTML/JS Code into my Vaadin WebApplication by creating an AbstractJavaScriptComponent . The Component almost works as intended.How do I call the passInfo ( ) method defined in the `` connector.js '' without having to manually click the Button defined in the innerHTML of the `` chessControll.JsLab...
com_*myname*_*applicationName*_JsLabel = function ( ) { var mycomponent = new chessControll.JsLabel ( this.getElement ( ) ) ; connector = this ; this.onStateChange = function ( ) { mycomponent = this.getState ( ) .boolState ; } ; mycomponent.click = function ( ) { connector.passInfo ( true ) ; } ; } ; var chessControll...
JavaScript Scope of Vaadin 's `` AbstractJavaScriptComponent ''
Java
I am trying to use putextra ( ) and getextra ( ) but my program is crashing after implementing itGo through my code and let me know my mistakeIf I am not using getextra ( ) and putextra ( ) the code is working flawlessly This is 1st class from where I am getting the valueNow the Second class where I am trying to Pass t...
public class Assess extends ListActivity { String itm ; ArrayAdapter < String > Adapter ; @ Overrideprotected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; getListView ( ) .setBackgroundResource ( R.drawable.background ) ; Adapter = new ArrayAdapter < String > ( this , android.R....
Implementing Getextra ( ) and Putextra
Java
I 've written a streams implementation that performs four simple reductions ( + and < ) on the lines of a file.At first I performed four streams , but I decided to write my own accumulator and combiner so that I could perform all four reductions in one stream . On small data sets ( 10,000,000 lines ) this reduces runti...
fileIn = new BufferedReader ( new InputStreamReader ( new URL ( args [ 0 ] .trim ( ) ) .openStream ( ) ) ) ; final Results results = fileIn.lines ( ) .parallel ( ) .skip ( 1 ) .map ( User : :parse ) .filter ( Optional : :isPresent ) .map ( Optional : :get ) .collect ( Results : :new , Results : :accumulate , Results : ...
Can Java 8 streams cause a O ( 1 ) memory reduction on unbounded data to become O ( n ) memory because of the underlying ForkJoin implementation
Java
Since I could n't find a standard implementation of it I created this little class , but I think something simple as this should exist somewhere already : The purpose of it is to exchange a value between two threads ( main thread + EDT in my case ) . From the code using the getValue ( ) method it looks almost like a Fu...
class ReturnValue { private var value = false private val latch = new java.util.concurrent.CountDownLatch ( 1 ) def setValue ( aValue : Boolean ) { value = aValue latch.countDown ( ) } def getValue ( ) = { latch.await value } }
How do you call this kind of concurrency related class ? And is there a standard implementation ?
Java
I have a rollback exception with hibernate on my service `` duplicateContract '' The problem is , I just ca n't debug that , there is an error with the persisted object somewhere but I have no clue ( it 's not a timeout or missing @ Transactional ) . How can I get more details for this exception ? ( maybe somewhere in ...
Caused by : org.springframework.transaction.UnexpectedRollbackException : JTA transaction unexpectedly rolled back ( maybe due to a timeout ) ; nested exception is javax.transaction.RollbackException at org.springframework.transaction.jta.JtaTransactionManager.doCommit ( JtaTransactionManager.java:1031 ) at org.springf...
How to get the SQL error origin of an UnexpectedRollbackException
Java
I found code examples in internet for reading the data from the latest version of Google Sheet as below : But I can not find any examples , to access a particular version of the Google Sheet and get a cells value in that revision.Also please let me know , if the above requirement can be completed using google spreadshe...
SpreadsheetService service = new SpreadsheetService ( `` Print Google Spreadsheet Demo '' ) ; service.setUserCredentials ( GOOGLE_ACCOUNT_USERNAME , GOOGLE_ACCOUNT_PASSWORD ) ; URL metafeedUrl = new URL ( SPREADSHEET_URL ) ; SpreadsheetEntry spreadsheet = service.getEntry ( metafeedUrl , SpreadsheetEntry.class ) ; URL ...
How to read data from a specific version of Google Sheet ?
Java
I´m developing an application for Liferay 6.1 EE GA3.Under the control panel , we have the section Private plugin installer where we can install / deploy new portlets . I was using the panel and the section was workng correctly.Then i tried to install a custom portlet . For some reason the installation failed and i rem...
< % @ include file= '' /html/portlet/admin/view.portal.jsp '' % > < % @ include file= '' /html/portlet/admin/init.jsp '' % > < c : choose > < c : when test= '' < % = permissionChecker.isOmniadmin ( ) % > '' > < % String tabs1 = ParamUtil.getString ( request , `` tabs1 '' , `` server '' ) ; boolean showTabs1 = false ; i...
Liferay 6.1 - Private Plugin installer `` disapear '' or is disabled in Control panel
Java
Sorry for really stupid question , I 'm learning a new language and taking this code : Why the output does not produce `` ] '' character ? Has it something to do with Unicode ? PostEdited : the variable E.c was not initialized for experimentation purpose .
public class Exercise01 { int i ; char c ; public static void main ( String [ ] args ) { Exercise01 E = new Exercise01 ( ) ; System.out.println ( `` i = `` + E.i ) ; System.out.println ( `` c = [ `` + E.c + `` ] '' ) ; } } /* Output : i = 0c = [ */
First Ever Java Program Incorrect Output
Java
I have the following code : This works fine on my computer and on my Android device . I get strings like 0product0 etc.BUT in production , on users ' Android devices , I get strings like : Does String.format ( ) not work OK when starting with a number ?
int color = 0 ; int number = 0 ; // ... s = String.format ( `` % dproduct % d '' , color , number ) ; ٠product٠٠product١٠product٢٠product٣٠product٤
String.format fails to format numbers on some devices ?
Java
I 'm using removeNumbers to remove all numbers in a given string with the regex '' ( ^| ) \\d+ ( $ | ( \\d+ ) + ( $ | ) | ) '' Here 's the code : Output : Is there any better way to do this ? Edit : As suggested by @ mbomb007 in his previous answer , the regex `` ( |^ ) [ \\d ] + ( | $ ) '' works as well :
public class Regex { private static String removeNumbers ( String s ) { s = s.trim ( ) ; s = s.replaceAll ( `` + '' , `` `` ) ; s = s.replaceAll ( `` ( ^| ) \\d+ ( $ | ( \\d+ ) + ( $ | ) | ) '' , `` `` ) ; return s.trim ( ) ; } public static void main ( String [ ] args ) { String [ ] tests = new String [ ] { `` 123 '' ...
Regex to find numbers in a string
Java
Just trying a hands-on the java.lang.Record . I have gone through the documentation and the JEP-359 for some understanding . So upon reading about the implicit declaration of the constructor I thought of mixing it up with an existing code generation library - Lombok ! Now what I 've ended up creating as a minimal repro...
import lombok.AllArgsConstructor ; @ AllArgsConstructorpublic record Java ( String version ) { } public final class Java extends java.lang.Record { private final java.lang.String version ; public Java ( java.lang.String version ) { /* compiled code */ } ... rest of the compiled code } public class MixOfWorlds { public ...
Java Records and Lombok annotation - IntelliJ
Java
my Splash activity does n't change , it only changes if I change the name to another.For example : '' SplashActivity '' - Start with a ModificationIf I change the theme to another color , I need to rename the activity to : '' SplashActivityy '' or some other name than it was.If I go back to the name `` SplashActivity '...
< ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < manifest xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : tools= '' http : //schemas.android.com/tools '' package= '' com.example.cobaiascreen '' > < application android : allowBackup= '' true '' android : icon= '' @ mipmap/ic_launcher ''...
Activity Theme is not changing
Java
i just stumbled onto this comment . in the 1.5 java source.what does this comment mean ? is it a reference to a book ? a spec ?
public static int lowestOneBit ( int i ) { // HD , Section 2-1 return i & -i ; }
cryptic comment in jdk source : // HD , Section 2-1
Java
Primitives are at it again , breaking rules , I learned before . Well not technically primitive but composed of them.I learned that whenever there 's no method more specific than rest , compile time error occurs as it happens here.Now comes primitives into the picture.Expected compile time errors occurs here.Now my que...
public static void caller ( ) { z5 ( ) ; // Error . Neither Integer , nor String is more specific z5 ( null ) ; // Error for the same reason } public static void z5 ( Integer ... integers ) { System.out.println ( `` Integer z5 called '' ) ; } public static void z5 ( String ... strings ) { System.out.println ( `` String...
Primitive vararg parameters in method overloading
Java
Recently , I 've noticed , it is possible to have : Is there a reason for this ?
class Test { public enum Season { WINTER , SPRING , SUMMER , FALL } Season field = Season.WINTER.SPRING ; // why is WINTER.SPRING possible ? }
In Java , why is it possible to qualify an Enum Constant with another Enum Constant ?
Java
Each time our new android app released , I need to update app info on our website . So I try to update the app info automatically , by read the AndroidManifest.xml in the apk when uploaded to server.I use AXMLResource and jdom2 to get the AndroidManifest.xml and parse it.But I always get , The prefix “ data ” for attri...
final Namespace NS = Namespace.getNamespace ( `` http : //schemas.android.com/apk/res/android '' ) ; zipFile = new ZipFile ( apkPath ) ; ZipEntry zipEntry = new ZipEntry ( `` AndroidManifest.xml '' ) ; inputStream = zipFile.getInputStream ( zipEntry ) ; AXMLResource axmlResource = new AXMLResource ( ) ; axmlResource.re...
Java parse xml with undeclared namespace
Java
I have a simple sticker widget that allows the user to select one of the stickers upon placing the widget . My problem is that once the device is restarted , the sticker reverts to the default one . How can I ensure that the user selected sticker remains regardless of whether the device is restarted or not ? An example...
public class SpraycanConfig extends Activity { int xawID ; AppWidgetManager xawm ; Context xc ; EditText xinfo ; //EasyTracker easyTracker ; protected void onCreate ( Bundle paramBundle ) { super.onCreate ( paramBundle ) ; Crashlytics.start ( this ) ; setContentView ( R.layout.scconfiglayout ) ; this.xc = this ; Bundle...
How to ensure user selected image does n't change after restart Android ?
Java
Is there any guarantee that an object will not be garbage collected while a thread holds its monitor ? e.g.In this case concretely , is there any guarantee that b will be non-null if thread2 ( ) is called while another thread is sleeping in thread1 ( ) ? Let 's just assume the whole of thread2 ( ) is executed while thr...
class x { private WeakReference < Object > r ; Object getMonitorObject ( ) { Object o = new Object ( ) ; r = new WeakReference < > ( o ) ; return o ; } void thread1 ( ) throws Exception { synchronized ( getMonitorObject ( ) ) { Thread.sleep ( 3000 ) ; } } void thread2 ( ) { Object b = r.get ( ) ; } }
Does Java guarantee that currently synchronized objects are not garbage collected ?
Java
I need to implement current formula.It is for scoring the nodes in a taxonomy . Basically , the score of a node depends on the amount of child nodes and their scores ( ( nodes ( h+1 ) ) is the amount of nodes on the next level and Cl ( concept ) is a set of children ) .In my usecase term frequencies are only defined fo...
1 / \ 2 3 | | 4 17 / \ 11 13 public static float calcScore ( int keyID , Map < Integer , Integer > frequencies , Map < Integer , Integer > subTaxonomy ) { float res = 0f ; int nodes = 0 ; if ( frequencies.containsKey ( keyID ) ) { return frequencies.get ( keyID ) + 0f ; } for ( Map.Entry < Integer , Integer > entry : s...
Mathematical formula to a recursive method
Java
I have some code that uses the Swing/AWT printing functionality that I want to unit test . It uses the systems native print dialog , but is there any way to get the JVM to intercept that and replace it with a mock during unit testing so that I can get a copy of the image that would be printed ? My code for printing is ...
Printable printable = getPrintable ( ) ; PrinterJob printJob = PrinterJob.getPrinterJob ( ) ; printJob.setPrintable ( printable ) ; if ( printJob.printDialog ( ) ) { try { printJob.print ( ) ; } catch ( PrinterException exception ) { ... } }
Unit tests for printing in Java Swing
Java
I made a Java agent which is attached to a JVM during runtime and instruments all the loaded project classes and inserts some logging statements . There are 11k classes in total . I measured the total time taken by the transform method of my ClassFileTransformer and it was 3 seconds . But the duration of the whole inst...
instrumentation.retransformClasses ( myClassesArray ) ; instrumentation.addTransformer ( new MyTransfomer ( ) , true ) ; instrumentation.retransformClasses ( retransformClassArray ) ; public class MyTransfomer implements ClassFileTransformer { private long total = 0 ; private long min = ... , max = ... ; public final b...
How to speed up runtime Java code instrumentation ?
Java
I have one repository in two different folders ( folder1 and folder2 ) . Within repositories has a `` oldFile '' fileIn the folder1 I do the following steps : After that , in the folder2 I do next steps : In this case I want to get a merge conflictAnd I want to see pulled files . I got the example from here.In pullResu...
echo 123 > oldFiletouch newFilegit add newFile oldFilegit commit -m `` Change the oldFile from folder1 and add the newFile '' oldFile newFilegit push origin master echo zxc > oldFile ; git add oldFile ; git commit oldFile -m `` Change oldFile from folder2 '' ObjectId oldHead = repository.resolve ( `` HEAD^ { tree } '' ...
JGit get pulled files
Java
I want to use CoreNLP in my Android project . But when I create a CoreNLP instance like this : The project links to the following .jar files : ejml-0.23.jar stanford-corenlp-3.4.1.jarstanford-corenlp-3.4.1-models.jarOn my desktop java environment with java 1.8.0_92 , this code runs correctly , but when running the code...
import java.util.Properties ; import edu.stanford.nlp.ling.CoreAnnotations ; import edu.stanford.nlp.neural.rnn.RNNCoreAnnotations ; import edu.stanford.nlp.pipeline.Annotation ; import edu.stanford.nlp.pipeline.StanfordCoreNLP ; import edu.stanford.nlp.sentiment.SentimentCoreAnnotations ; import edu.stanford.nlp.trees...
'Ca n't return head of null or leaf Tree ' with CoreNLP on Android
Java
In the documentation for public Object get ( Object obj ) method in the Field class it is stated that The value is automatically wrapped in an object if it has a primitive type.and for public void set ( Object obj , Object value ) that If the underlying field is of a primitive type , an unwrapping conversion is attempt...
public class Test { int i = 1 ; public static void main ( String [ ] args ) throws Exception { Test inst = new Test ( ) ; Class < ? > clazz = inst.getClass ( ) ; Field fi = clazz.getDeclaredField ( `` i '' ) ; int ii = ( int ) fi.get ( inst ) ; Integer iii = new Integer ( ii * 2 ) ; fi.set ( inst , iii ) ; } }
Whats the purpose of the primitive getter/setter in Field ?
Java
So , lets say I have some game , take Pong for example . Obviously , you generally speaking do n't want to mix game-logic into graphics classes , so the class for Ball or Paddle is sepearte from the JPanel which actually draws them . Ball has the movement logic for the ball , its current location , hit detection , etc ...
public class Ball { static Rectangle hitbox = new Rectangle ( 0,10,20,20 ) ; static void checkHit ( ) { if ( hitbox.intersects ( Paddle.hitbox ) //do something } } public class DrawMyStuff extends JPanel { void paintComponent ( Graphics g ) { super.paintComponent ( g ) ; setBackground ( Color.BLACK ) ; Graphics2D g2d =...
Is it bad practice to use swing and awt classes for my non-graphics related classes in my programs ?
Java
I have the following as AppCompatSpinner 's entries : Upon selecting Pick a time.. , a TimePickerDialog is opened and the user is allowed to choose a time . Here 's how : Upon selecting Pick a time.. the first time , TimePickerDialog is successfully opened and the chosen time is shown but when I choose it again or clic...
< string-array name= '' startTimeList '' > < item > Now < /item > < item > Pick a time.. < /item > < /string-array > startTimeSpinner.setOnItemSelectedListener ( new AdapterView.OnItemSelectedListener ( ) { @ Override public void onItemSelected ( AdapterView < ? > adapterView , View view , int i , long l ) { // startTi...
AppCompatSpinner 's entries not opening TimePickerDialog on selecting it second time . Please see details
Java
I had a coding interview over the phone and was asked this question : Given a String ( for example ) : `` aksdbaalaskdhfbblajdfhacccc aoudgalsaa bblisdfhcccc '' and an expression ( for example ) : `` a+b+c- '' where : + : means the char before it is repeated 2 times - : means the char before it is repeated 4 times Find...
1 ) aksdbaalaskdhfbblajdfhacccc aoudgalsaa bblisdfhcccc ^^ ^^ ^^^^ aa bb cccc2 ) aksdbaalaskdhfbblajdfhacccc aoudgalsaa bblisdfhcccc ^^ ^^ ^^^^ aa bb cccc3 ) aksdbaalaskdhfbblajdfhacccc aoudgalsaa bblisdfhcccc ^^ ^^ ^^^^ aa bb cccc4 ) aksdbaalaskdhfbblajdfhacccc aoudgalsaa bblisdfhcccc ^^ ^^ ^^^^ aa bb cccc import java...
Finding the Number of Times an Expression Occurs in a String Continuously and Non Continuously
Java
I am designing a game engine in Java.At the core of this engine exist the two classes Asset and Attribute , where an Asset has a list of Attributes . Most Attributes need no link back up to their Attribute , meaning that Attributes can and often do appear in the lists of more than one Asset . However , there is an exte...
public void addAttribute ( Attribute attribute ) { if ( attribute instanceof UniqueAttribute ) ( ( UniqueAttribute ) attribute ) .setAsset ( this ) ; attributeList.add ( attribute ) ; } asset.addAttribute ( new UniqueAttribute ( asset ) ) ;
Java : Enforcing doubly linked objects
Java
I have a question about Java generics . Say I have the following interface : An example of usage : I would also like to be able to add Something < Integer > , Something < Double > , ... to the a Manager < Number > . I would say I have to change the signature of the add-function : So far , so good . Let 's look at a pos...
public static class Something < T > { public void set ( T t ) { } } public static interface Manager < T > { public void add ( final String key , final Something < T > o ) ; public Something < T > get ( final String key ) ; } final Manager < Number > m = ... ; m.add ( `` key '' , new Something < Number > ( ) ) ; m.get (...
Java - generics & wildcards & interface versus implementation
Java
What 's the sense of this class definition , what 's kind of class is that ?
class Node < K extends Comparable < ? super K > , V >
Class definition class name < >
Java
I 'm currently exploring Guice capabilities and faced a strange behaviour - when I declare variable asinjection works as expected , but when I want to declare dragon2 as interface ( it implements Creature ) , i. e. I get an error No implementation for warlock.rincewind.creatures.Creature annotated with @ com.google.inj...
@ Inject @ Named ( `` dragon '' ) Dragon dragon2 ; @ Inject @ Named ( `` dragon '' ) Creature dragon2 ; @ Named ( `` dragon '' ) @ Providespublic Dragon providesDragon ( ) { Dragon d = new Dragon ( `` Morkeleb '' ) ; return d ; }
@ Provides with @ Named does n't work for supertype declared variables
Java
Using ZeroMQ .Context and .Socket instances , I am able to push/pull messages for example below my code for a Queue like setup : My questions are : Q1 : How to implement an active / standby mode in queues ? I mean there will be 2 queues , created for one host and port , if one queue ( the active ) fails , another ( i.e...
ZMQ.Context context = ZMQ.context ( 1 ) ; // Socket to send messages on ZMQ.Socket sender = context.socket ( ZMQ.PUSH ) ; sender.bind ( `` tcp : //*:5557 '' ) ; // Send messages sender.send ( `` 0 '' , 0 ) ; ZMQ.Socket receiver = context.socket ( ZMQ.PULL ) ; receiver.connect ( `` tcp : //localhost:5557 '' ) ; // recei...
How to implement an active & standby queue job-processing system in JeroMQ ?
Java
I am new to java . I had a doubt .
class ArrTest { public static void main ( String args [ ] ) { int i = 0 ; int [ ] a = { 3,6 } ; a [ i ] = i = 9 ; System.out.println ( i + `` `` + a [ 0 ] + `` `` + a [ 1 ] ) ; // 9 9 6 } }
Why the following code does not throw IndexOutOfBoundsException , and print out 9 9 6 ?
Java
i was working on the basic java program and i found verry funny thing which i am sharing with you . foo ( ) gives output ( s==s1 ) = false and bar gives ( s==s1 ) = true.I want to know why this happens .
public class StringTest { public static void main ( String [ ] args ) { foo ( ) ; bar ( ) ; } public static void foo ( ) { String s = `` str4 '' ; String s1 = `` str '' + s.length ( ) ; System.out.println ( `` ( s==s1 ) = `` + ( s1==s ) ) ; } public static void bar ( ) { String s = `` str4 '' ; String s1 = `` str '' + ...
Why do I get different results when comparing strings after using different concatenation in Java ?
Java
I have a code where my client send an excel file to the server . The server ( SpringBoot ) needs to 'translate ' the MultiplartFile to an excel File.From then , the data needs to be inserted into a database.However , I never need to generate an excel but rather should insert the data from the spreadsheet into the datab...
@ RequestMapping ( value = `` /insert '' , method = RequestMethod.POST , consumes = `` multipart/form-data '' ) @ ResponseBodypublic MyMessage insertExcell ( @ RequestPart ( `` typeFile '' ) String typeFile , @ RequestPart ( `` uploadFile '' ) MultipartFile multipart , @ RequestPart ( `` dataUser '' ) DataUser dataUser...
Save uploaded excel in database
Java
I 'm using a PostUpdateEventListener registered viaand a few other listeners in order to track changes made by Hibernate . This works perfectly , however , I see a problem there : Let 's say , for tracking some amount by id , I simply executeon every POST_COMMIT_UPDATE ( let 's ignore other operations ) . The problem i...
registry.appendListeners ( EventType.POST_COMMIT_UPDATE , listener ) amountByIdConcurrentMap.put ( id , amount ) ;
Reliably tracking changes made by Hibernate
Java
Is it good programming practise , when dealing with multiple classes that need the same instance of variables , to create one central one ? For example : I have a class with a set amount of variablesI have another class that needs the same variablesAnd another that needs the same variables as the firstSo I have three c...
chatWindow.variables.username = userField.getText ( ) ; classOne.variableClass.VariableName = false ;
Good programming practices with centralizing variables
Java
Suppose you start with an auto-generated methodAnd write a test for itThen 3 month from now you decide that a more appropriate name for the method would be changeKeyTo . You refactor your production code and end up with : Life is good , however , your test name remained unchangedHow do you deal with something like this...
public void setKey ( Key key ) { this.key = key ; } @ Testpublic void testSetKey ( ) public void changeKeyTo ( Key key ) { this.key = key ; } @ Testpublic void testSetKey ( )
How to refactor test code together with production code ?
Java
Our application sends strings which then shall be localized on client side . Sometimes those are whole strings , sometimes only substring , so we have to mark them . It would be the best if it only used Unicode as it would n't require any protocol changes.Example : where 10 is length in cm but it should be converted so...
`` Length : ( mark ) 10 ( mark ) ''
Which subset of Unicode symbols should I use to mark special substrings in text ?
Java
I use two Interfaces : My problem that I want to register a Distributor in a Distributor e.g.Distributor < Object > ==register== > Distributor < String > My first thought was to change the register method to register ( Receiver < ? extends T > receiver ) . But if I want to get the Classes the receiver is intrested in t...
public interface Receiver < T > { public void receive ( T obj ) ; public Set < Class < ? extends T > > getInterests ( ) ; } public interface Distributor < T > extends Receiver < T > { public void register ( Receiver < T > receiver ) ; } public void register ( Receiver < ? extends T > receiver ) { Set < Class < ? extend...
Generic Chaos Java
Java
Here is the original link , http : //electrotek.wordpress.com/2008/08/06/singleton-in-java-the-proper-way/I am asking why we can call the function doStuff this way in Java .
public enum YourSingleton { INSTANCE ; public void doStuff ( String stuff ) { System.out.println ( `` Doing `` + stuff ) ; } } YourSingleton.INSTANCE.doStuff ( `` some stuff '' ) ;
Singleton – the proper way
Java
I am implementing a Java application using the Swing GUI framework on macOS . When using the system look and feel and a screen menu bar , Swing automatically inserts a search field called Spotlight for Help into the first menu labelled `` Help '' of the menu bar of a frame : As my application is localized , the English...
System.setProperty ( `` apple.laf.useScreenMenuBar '' , `` true '' ) ; try { UIManager.setLookAndFeel ( UIManager.getSystemLookAndFeelClassName ( ) ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } JFrame frame = new JFrame ( ) ; JMenuBar menuBar = new JMenuBar ( ) ; JMenu helpMenu = new JMenu ( `` Help '' ) ; me...
How to insert Spotlight for Help into localized macOS applications in Java ?
Java
While investigating the subtler consequences of generational garbage collectors on application performance , I have hit a quite staggering discrepancy in the performance of a very basic operation – a simple write to a heap location – with respect to whether the value written is primitive or a reference.The microbenchma...
@ OutputTimeUnit ( TimeUnit.NANOSECONDS ) @ BenchmarkMode ( Mode.AverageTime ) @ Warmup ( iterations = 1 , time = 1 ) @ Measurement ( iterations = 3 , time = 1 ) @ State ( Scope.Thread ) @ Threads ( 1 ) @ Fork ( 2 ) public class Writing { static final int TARGET_SIZE = 1024 ; static final int [ ] primitiveArray = new i...
What can explain the huge performance penalty of writing a reference to a heap location ?
Java
I 'm making my very own version of Java 's Stream library for fun . Here 's my class signature : Also , I wrote a basic infinite stream iterator that would generate an infinite list based on the given function : The function generate is a special case of iterate that repeats a given element forever . In the function ab...
class Stream < T > { Supplier < T > head ; Supplier < Stream < T > > tail ; ... } public static < T > Stream < T > iterate ( T first , Function < T , T > f ) { return new Stream < T > ( ( ) - > first , ( ) - > { T nextElem = f.apply ( first ) ; if ( nextElem == null ) { return generate ( ( ) - > null ) ; } else { retur...
Filter Function Not Lazy
Java
I have the sample code below : and the following exception was thrown My question is why I am not able to add new string to my list ?
String [ ] patternArray = { `` 1 '' , '' 2 '' , '' 3 '' } ; List < String > patternCheck = Arrays.asList ( patternArray ) ; patternCheck.add ( `` 4 '' ) ; Exception in thread `` main '' java.lang.UnsupportedOperationException at java.util.AbstractList.add ( Unknown Source ) at java.util.AbstractList.add ( Unknown Sourc...
List throwing UnsupportedOperationException
Java
There many ways to get a good security for REST ( easy ) services . I tried already . In this case only is a Basic Authentication needed . So , not based on login , RequestFilters , etc . Please focus on this example . While adding security to one RestEasy 'post ' method , I keep on getting 401 exceptions . How can I g...
< user username= '' wineuser '' password= '' winepass '' roles= '' winer '' / > < security-constraint > < web-resource-collection > < web-resource-name > wine secret < /web-resource-name > < url-pattern > /rest/wines/secret < /url-pattern > < http-method > POST < /http-method > < /web-resource-collection > < auth-const...
Handling a basic/base64 security 401 exception in RestEasy and Tomcat
Java
I added this recursive BubbleSort algorithm to my game which runs on lwjgl . I 'm trying to sort an ArrayList of `` Cloud '' objects by a float which is the speed of this cloud.For some reason sometimes I get a `` java.lang.StackOverflowError '' at the line I invoke the method in itself.Here 's the code : And here are ...
public void sort ( ) { for ( int i = 0 ; i < clouds.size ( ) - 1 ; i++ ) { Cloud cl1 = clouds.get ( i ) ; Cloud cl2 = clouds.get ( i + 1 ) ; if ( cl1.getSpeed ( ) < cl2.getSpeed ( ) ) { continue ; } clouds.set ( i , cl2 ) ; clouds.set ( i+1 , cl1 ) ; this.sort ( ) ; } } Sat May 04 20:28:45 CEST 2013 ERROR : nulljava.la...
BubbleSort StackOverflowError
Java
I have a static function with the following signature for a generic type Twhich should return a list of map keys with some property.Now I want to pass a generic HashMap of type Sin calling the static function within a generic class , which has the map as a member variable.I have listed a minimal code example below.Howe...
public static < T > List < T > sortMap ( Map < T , Comparable > map ) Map < S , Double > map required : Map < T # 1 , Comparable > found : Map < T # 2 , Double > reason : can not infer type-variable ( s ) T # 1 ( argument mismatch ; Map < T # 2 , Double > can not be converted to Map < T # 1 , Comparable > ) public clas...
Inferring a generic type from a generic type in Java ( compile time error )
Java
What is the reason of the exception message complains about duplicate key but shows the value instead ? Instead of show `` John '' as the duplicated key , it show `` 40 ''
List < Employee > employees = new ArrayList < > ( ) ; employees.add ( new Employee ( `` John '' , 40 ) ) ; employees.add ( new Employee ( `` John '' , 30 ) ) ; Map < String , Integer > map = employees.stream ( ) .collect ( Collectors.toMap ( Employee : :getName , Employee : :getAge ) ) ; Exception in thread `` main '' ...
Duplicate Key - misleading exception information ?
Java
Apologies that is probably the worst Title I 've used but I ca n't quite think how to word it.I 'm calling a method table.getColData ( COL_1 ) which returns a genericI am calling it twice and getting two lists of strings . I want to concatenate these and have ended up with this - which works nicely I think . I ca n't f...
public < T extends Object > List < T > getColData ( final String col ) List < String > a = table.getColData ( col1 ) ; List < String > b = table.getColData ( col2 ) ; List < String > c = Stream.concat ( a.stream ( ) , b.stream ( ) ) .collect ( Collectors.toList ( ) ) ;
casting & generics to enable list concatenation in Java 8
Java
I am trying to develop an ObjectPool , which can be used with any Object without changing the source of neither the Pool nor the Object - but I can´t find any way to write the get ( ) -function ( `` Maincode '' getting some Object from Pool ) as there is a Type-Mismatch ( Can not convert from Object to TestObject ) Her...
public Object get ( ) { int first = availableObjects.get ( 0 ) ; availableObjects.remove ( 0 ) ; return objects.get ( first ) ; } TestObject test = objectPoolS.get ( ) ; public class ObjectPoolS < T > { int numberOfObjects ; boolean autoExtending ; T baseObject ; ArrayList < T > objects ; ArrayList < Integer > availabl...
Generic ObjectPool - how to return a generic class ?
Java
I was going through the Martin Odersky 's book Programming in Scala with it 's section on abstract modules , and his paper Scalable Component Abstractions : http : //lampwww.epfl.ch/~odersky/papers/ScalableComponent.pdfMy takeaway is that by making your modules abstract classes instead of objects ( or classic static , ...
abstract class myModule { // this is effectively an abstract module , whose concrete // components can be configured by subclassing and instantiating it class thing { } class item { } object stuff { } class element { } object utils { } }
Scala-style abstract modules in C # or other languages ?
Java
In my Java 8 app , I am scanning for whitespaces in text passed in . But \s in my Regular Expression does n't capture all whitespaces . The one whitespace that I 've found that it does n't capture so far in my testing is Non-breaking Space ( Unicode 00A0 ) . This was my regular expression that was running into that iss...
Pattern p = Pattern.compile ( `` \\s '' ) ; Pattern p = Pattern.compile ( `` [ \\s\\h ] '' ) ;
\s does n't actually capture all whitespace characters
Java
I come from an Actionscript3 background and this is my first time writing any Java in my life . Hashtables seem to be similar to Dictionaries in Flash , but I want to make sure I am using them correctly . I believe the Hashtable is typed to accept Strings as keys and Typefaces as objects . Is this correct ? Is there a ...
package com.typeoneerror.apps.app_name.utils ; import android.content.Context ; import android.graphics.Typeface ; import java.util.Hashtable ; public class FontRegistry { private static FontRegistry _instance ; private Context _context ; private Hashtable < String , Typeface > _fonts ; private FontRegistry ( ) { _font...
Is Hashtable appropriate for storing assets ?
Java
I 'm trying to understand Generic types in Java , and in theory it looks understandable , but when I need to apply it to real code I have problem . I want to declare abstract method which will return generic type . Let 's assume that I have some empty interface called Magicable and 2 class implements it : Magican and W...
/*1*/protected abstract < T extends Magicable > List < T > getMagicables ( ) ; /*2*/protected abstract List < ? extends Magicable > getMagicables ( ) ; /*3*/protected abstract List < Magicable > getMagicables ( ) ; @ Overrideprotected List < Magican > getMagicable ( ) { .. } public void < T extends Magicable > T getOne...
Difference between using wildcards and declaring generic type in abstract method in Java
Java
I 'm trying to ingest a mp4 file and make it a timelapse . It works with the code attached below . However , the output file has frame rate of 16*originalFrameRate . Since I do n't intend to play it as a slow motion video I 'd prefer to drop those redundant frames to make the output file smaller.I was unable to find an...
Movie inputMovie = MovieCreator.build ( fileUri ) ; List < Track > videoTracks = new LinkedList < > ( ) ; for ( Track track : inputMovie.getTracks ( ) ) { if ( track.getHandler ( ) .equals ( `` vide '' ) ) { videoTracks.add ( track ) ; } } final int speedByFactorOf = 16 ; Movie outputMovie = new Movie ( ) ; AppendTrack...
mp4parse timelapse frame rate
Java
I 'm trying to solve the multithreaded bank account problem* without using locks but using multiversion concurrency control . It 's working . It 's just a bit slow . How can I speed it up ? ( * ) I have 5 users , each starting with 200 - each randomly withdrawing 100 and depositing 100 into another bank account owned b...
import java.util . * ; import java.util.concurrent . * ; import java.util.function.Consumer ; import java.util.function.Function ; public class ConcurrentWithdrawer { private Map < String , Integer > database = new HashMap < > ( ) ; private int transactionCount = 0 ; private final List < Transaction > transactions = Co...
Is it possible to solve the multithreaded bank account problem fast without locks ?
Java
I have very simple thing to do , i have list of persons like this : Result of this array should be : Adam ( true ) , John ( false ) So i need to return list of latest entries from users , in this case John first confirmed that he is attending , then he changed his mind and told that he is not attending so i 'm returnin...
[ { name : John , date : 01-01-2018 , attend : true } , { name : Adam , date : 01-01-2018 , attend : false } , { name : Adam , date : 01-02-2018 , attend : true } , { name : JOHN , date : 01-02-2018 , attend : false } ]
Good way to filter list distincted by property and ordered by date
Java
given the interfaces ( which are very large and generated out of language definitions ) : Now compiling the interface VisitorA ( containing of about 2.000 overloaded methods ) needs about 10s.Compiling the interfaces VisitorB and VisitorC needs each about 1.5 min.But when we try to compile the interface VisitorD , the ...
interface VisitorA { default void visit ( ASTA1 node ) { ... } ... default void visit ( ASTA2000 node ) { ... } } interface VisitorB extends VisitorA { default void visit ( ASTB1 node ) { ... } ... default void visit ( ASTB1000 node ) { ... } // due to language embedding all visit methods of VisitorA // must be overwri...
Java8 slow compiling for interfaces with thousands of default methods with the same name
Java
The following code for Integer uses object interning : It is not clear from API documentation whether this code for Boolean also uses interned object : Obviously , it may . But does it have to ? UPDATEI agree that source code can explain what actually happens ( BTW , thanks for the answers ) . To make the question less...
Integer.valueOf ( `` 1 '' ) Boolean.valueOf ( `` true '' ) String str = `` true '' ; if ( Boolean.valueOf ( str ) == Boolean.TRUE ) { ... }
Is boolean interned in Java ?
Java
I have a method to rotate images but I always receive an OutMemoryError , but my images in the gallery iare taken from camera and size width is 5000~ from phone I resized photo to width 1280 and height 960my first method for show and resize image is And my method for rotate image is where is my error ? * -- -- -- -- --...
public static Boolean ShowImagesCapture ( Context context , Uri PATH_IMAGE , ImageCropView view , int width , int height ) { int orientation=0 ; Boolean success = true ; try { Bitmap bitmap =null ; if ( Build.VERSION.SDK_INT < 19 ) { String selectedImagePath = getPath ( PATH_IMAGE , context ) ; bitmap = BitmapFactory.d...
Android image resize error memory
Java
My IDE ( IntelliJ IDEA ) is telling me that I have the option to remove the braces on this if statement : To become : I understand how this makes sense , and it 's tempting to lose the indent , but my concern is that readability may suffer . The latter looks cleaner , but is the space saved worth the potential confusio...
if ( objectIsOfTypeFoo ) { if ( objectOfTypeFooIsShared ) { // do something with Object of type Foo knowing that it 's shared ... } else { // do something with Object of type Foo knowing that it 's not shared ... } } else if ( objectIsOfTypeBar ) { ... } if ( objectIsOfTypeFoo ) if ( objectOfTypeFooIsShared ) { // do s...
Should multiple if statements like `` if ( condition ) if ( condition ) ... '' be avoided in Java ?
Java
I have a BigDecimal List such as : Then , I have another List of Integers : These integers refer to the index by which I want to reorder the first list . So , I would like to reorder the first list to be : I 'm using Java 8 .
[ 50.0,26.2,29.3 ] [ 2,1,0 ] [ 29.3,26.2,50.0 ]
How to Order one list by the index values stored in another list
Java
I am creating a custom class to set the max height of a NestedScrollView , based on the answer provided in this StackOverflow question : How to set the Maximum Height for a NestedScrollView in Android ? However , when I include the custom class ( MaxHeightNestedScrollView ) in my activity_main.xml code layout , there i...
import android.content.Context ; import android.util.AttributeSet ; import androidx.annotation.NonNull ; import androidx.annotation.Nullable ; import androidx.core.widget.NestedScrollView ; public class MaxHeightNestedScrollView extends NestedScrollView { private int maxHeight = -1 ; public MaxHeightNestedScrollView ( ...
Android : Custom class for setting the max height of a NestedScrollView does not work ( there is no scrollbar )
Java
Due to a bug in the sigar library version I am using ( returns bogus values for swap ) , I tried using com.sun.management.OperatingSystemMXBean instead . This worked fine and gave me the desired results ( on Windows ) .However this breaks with java 9 . Is there another way to query swap file / partition information usi...
Class < ? > sunMxBeanClass = Class.forName ( `` com.sun.management.OperatingSystemMXBean '' ) ; sunMxBeanInstance = sunMxBeanClass.cast ( ManagementFactory.getOperatingSystemMXBean ( ) ) ; getFreeSwapSpaceSize = getMethodWithName ( sunMxBeanClass , `` getFreeSwapSpaceSize '' ) ; getTotalSwapSpaceSize = getMethodWithNam...
Querying swap space in java 9
Java
& & is a short-circuit operator evaluated from left to right , so if the operand on the left side of & & operator is evaluated to false , evaluation should not continue . BUT I expected that the ++ should be evaluated before & & because it has higher precedence , and ( from the link ) : Operators with higher precedence...
int mask = 2 ; int count = 0 ; if ( ! ( mask > 1 ) & & ++count > 1 ) { mask += 100 ; } System.out.println ( mask + `` `` + count ) ;
Java operator precendece confusion & & and ++
Java
I 'm a Java programmer . I have little knowledge on C # . But from the blogs I have read , Java supports only pass-by-value-of-reference whereas in C # the default is pass-by-value-of-reference but the programmer can use pass by reference if needed . I have penned down my understanding of how a swap function works . I ...
public static void Main ( ) { String ONE = `` one '' ; //1 ChangeString ( ONE ) ; //2 Console.WriteLine ( ONE ) ; //3 String ONE = `` ONE '' ; //4 ChangeString ( ref ONE ) ; //5 Console.WriteLine ( ONE ) ; //6 } private static void ChangeString ( String word ) { word = `` TWO '' ; } private static void SeedCounter ( re...
how does a swap method work in C # at a memory level ?
Java
I 'm looking for a java api that will correctly identify if a given ip address is private or local . This code seems to work for most ipv4/ipv6 addresses : Particularly , it identifies `` fec0 : : '' as a local/private type address but it does not identify , for example , `` fc00 : : '' or `` fd00 : : '' as local/priva...
boolean isLocalIp = InetAddress.getByName ( ipAddr ) .isSiteLocalAddress ( ) || InetAddress.getByName ( ipAddr ) .isLinkLocalAddress ( ) || InetAddress.getByName ( ipAddr ) .isLoopbackAddress ( ) ;
Is there a java api that will identify the ipv6 address fd00 : : as local/private ?
Java
I am working on a bytecode instrumentation project . Currently when handling objects , the verifier throws an error most of the time . So I would like to get things clear concerning rules with objects ( I read the JVMS but could n't find the answer I was looking for ) : I am instrumenting the NEW instruction : original...
NEW < MyClass > DUPINVOKESPECIAL < MyClass. < init > > NEW < MyClass > DUPINVOKESTATIC < Profiler.handleNEW > DUPINVOKESPECIAL < MyClass. < init > >
Bytecode and Objects
Java
While making up some arrays I noticed that prints out but only prints the stack location . I know char and String are both very different , but how come the JVM knows to output chars for the first and only a stack location for the second ? I am using IntelliJ and the command System.out.println ( javaArray ) ;
char [ ] javaArray = { ' j ' , ' a ' , ' v ' , ' a ' } ; java String [ ] javaStringArray = { `` j '' , '' a '' , '' v '' , '' a '' } ;
Java Array Char And String Difference In Array
Java
It is said in manual , that if child does not implement Scrollable , then JScrollPane rely on preferredSize properties of it 's content.Apparently this is not true for me . I am increasing preferred height , but JScrollPane does not feel or react on it .
package tests ; import java.awt.BorderLayout ; import java.awt.Color ; import java.awt.Dimension ; import java.awt.event.ActionEvent ; import javax.swing.AbstractAction ; import javax.swing.JFrame ; import javax.swing.JPanel ; import javax.swing.JScrollPane ; import javax.swing.Timer ; import org.slf4j.Logger ; import ...
How to implement JScrollPane child behavior ?
Java
I am trying to deserialize the following XML : My Jackson classes are : Bar is identical , just a different class name . ( In the real code they are different , this is just an example ) .And the root class isWhen I try to deserialize the XML , using this codeThe result is this ( note the lack of `` AAA '' ) : However ...
< root > < foo name= '' AAA '' / > < bar name= '' BBB '' / > < foo name= '' CCC '' / > < /root > @ Datapublic class Foo { @ JacksonXmlProperty ( isAttribute = true ) private String name ; } @ Datapublic class Root { @ JacksonXmlProperty ( localName = `` foo '' ) @ JacksonXmlElementWrapper ( useWrapping = false ) privat...
Jackson XML deserialization skips field when using multiple useWrapping = false
Java
I need a function which can calculate the mathematical combination of ( n , k ) for a card game . My current attempt is to use a function based on usual Factorial method : It 's working very well but the matter is when I use some range of number ( n value max is 52 and k value max is 4 ) , it keeps me returning a wrong...
static long Factorial ( long n ) { return n < 2 ? 1 : n * Factorial ( n - 1 ) ; } static long Combinatory ( long n , long k ) { return Factorial ( n ) / ( Factorial ( k ) * Factorial ( n - k ) ) ; } long comb = Combinatory ( 52 , 2 ) ; // return 1 which should be actually 1326
Combinatory issue due to Factorial overflow
Java
I am working on a small java bytecode instrumentation tool . The general idea is to have all of a class methods renamed with a _CONGU suffix , creating then proxy methods with the original method names that will call their _CONGU counterparts . For instance , if a class C contains a int m ( ) { return 1 ; } method , th...
Fraction fraction = new Fraction ( 4 , 1 ) ;
Wrong number of arguments in stack when trying to instrument java bytecode
Java
I replied to a question earlier about thread safety which did not get a definite answer ( I think ) .So I have been trying to convince myself that the design is broken ( visibility ) by having thousands of threads read and write that object - but I have not been able to get anything unexpected . That is obviously not a...
public class IsItSafe implements Cloneable { private int foo ; private int bar ; public IsItSafe foo ( int foo ) { IsItSafe clone = clone ( ) ; clone.foo = foo ; return clone ; } public IsItSafe bar ( int bar ) { IsItSafe clone = clone ( ) ; clone.bar = bar ; return clone ; } public int getFoo ( ) { return foo ; } publ...
How can one break this ( non ? ) thread safe object ?
Java
Taken from the official Java tutorial by Oracle , see question 2 here ( boilerplate by me ) .The answer says that studentName is not eligible for garbage collection since the array students still references it . However , the final line prints `` Peter Smith '' , so to me it seems wrong that students [ 0 ] references s...
public static void main ( String [ ] args ) { String [ ] students = new String [ 10 ] ; String studentName = `` Peter Smith '' ; students [ 0 ] = studentName ; studentName = null ; System.out.println ( students [ 0 ] ) ; }
When setting an array element to a String object , does the element reference the object ?
Java
Using Java 8 , I get a compiler error for the following code : So essentially the compiler says `` I know you return boolean but you should n't , and if you do n't I 'm not sure what method to use '' instead of `` oh you 're returning boolean , you must mean the Predicate version of the method '' ? How does this confus...
public class Ambiguous { public static void call ( ) { SomeDataClass data = new SomeDataClass ( ) ; callee ( data , SomeDataClass : :getString ) ; // compiler errors : // 1. at callee method name : // The method callee ( SomeDataClass , Function < SomeDataClass , String > ) is ambiguous for the type Ambiguous // 2. at ...
Function and Predicate parameter ambiguous ?
Java
I am trying to design a data model which can hold a very large amount of data , does anyone with experience in large volumes of data have any feedback on this , ie : Based on what I have read , the only way to get transactional integrity on inserting a Transaction and updating balance is to make it one entity group.How...
// example only , not meant to compilepublic class TransactionAccount { private long balance ; private List < Transaction > transactions = new ArrayList < Transaction > ( ) ; ... . public long getBalance ( ) { return balance ; } } private class Transaction { public Date date ; public long amount ; }
Transactions over very very large entity group
Java
I am a bit confused about this method reference syntax.counter ( ) expects a BiFunction however HighTemp : :lessThanTemp is a valid argument despite HighTemp.lessThanTemp ( ) only taking one argument.What exactly is happening in the line : if ( f.func ( vals [ i ] , v ) ) ? MCVE :
import java.util.function.BiFunction ; class Demo { static class HighTemp { private int hTemp ; HighTemp ( int ht ) { hTemp = ht ; } boolean lessThanTemp ( HighTemp ht2 ) { return hTemp < ht2.hTemp ; } } static < T > int counter ( T [ ] vals , BiFunction < T , T , Boolean > f , T v ) { int count = 0 ; for ( int i=0 ; i...
Confusion about two-argument method reference
Java
This is somewhat of a follow up on Java8 retrieving lambda setter from class.I 'm trying to get a getter method for a given fieldThis is the underlying method : This does not compile , due to a type mismatch : This however does compile : And , to my surprise , this does work using the getter which was retrieved above :...
public < T , R > IGetter < T , R > getGetter ( Class < T > clazz , Field field ) { Class < R > fieldType = null ; try { fieldType = ( Class < R > ) field.getType ( ) ; } catch ( ClassCastException e ) { error ( `` Attempted to create a mistyped getter for the field `` + field + `` ! `` ) ; } return getGetter ( clazz , ...
Ensuring type safety on generic lambda expression
Java
I 'm reading the source of java.util.concurrent.ArrayBlockingQueue , and found some code I do n't understand : Notice this line : Why it does n't use this.lock directly , but assigns it to a local variable ?
private final ReentrantLock lock ; public boolean offer ( E e ) { if ( e == null ) throw new NullPointerException ( ) ; final ReentrantLock lock = this.lock ; lock.lock ( ) ; try { if ( count == items.length ) return false ; else { insert ( e ) ; return true ; } } finally { lock.unlock ( ) ; } } final ReentrantLock loc...
Why it does n't use the instance field directly , but assigns it to a local variable ?
Java
When calling out the function testFunc ( ) , I am not using the syntax Apples.testFunc ( ) . Yet the code runs successfully . How so ?
class Apples { public static void main ( String args [ ] ) { testFunc ( ) ; } public static void testFunc ( ) { System.out.println ( `` Hello world ! `` ) ; } }
How a static method call works in Java ?
Java
I am currently evaluating implementations between Apache StopWatch and Guava 's Stopwatch and the split functionality in the former intrigued me , but I am struggling to understand what exactly it does , and what value it has.According to the documentation for StopWatch : https : //commons.apache.org/proper/commons-lan...
StopWatch stopwatch = StopWatch.createStarted ( ) ; do something for 5 secondsstopwatch.split ( ) ; do something for 10 secondsstopwatch.stop ( ) ; System.out.println ( stopwatch.getTime ( ) ) ; System.out.println ( stopwatch.getSplitTime ( ) ) ; StopWatch stopwatch = StopWatch.createStarted ( ) ; do something for 5 se...
What is the point of Apache Lang3 StopWatch.split ( ) ?
Java
I have a div that is a save button that has an awesome font symbol . After clicking the div , a new CSS class disabled is added where the opacity is reduced to visually signal the clicking of the button . After the save event the disabled CSS class is removed again and the button is fully visible again . If I try to ve...
driver.findElement ( By.cssSelector ( `` .save-button '' ) ) .click ( ) ; driver.findElement ( By.cssSelector ( `` .save-button .disabled '' ) ) ;
How to listen to CSS change in Selenium ?
Java
I 'm having an issue with libgdx skin . When the app is paused or goes into the background and then reopens all my scene2d textures are just showing up black . I assume that the underlying textures need to be reloaded.I 'm creating my skin using the following codeMy question is if there any way that I can detect when t...
FileHandle jsonFile = Gdx.files.internal ( `` ui/uiskin.json '' ) ; FileHandle atlasFile = Gdx.files.internal ( `` ui/uiskin.atlas '' ) ; TextureAtlas atlas = new TextureAtlas ( atlasFile ) ; skin = new Skin ( jsonFile , atlas ) ;
Libgdx reload scene2d skin after application hidden
Java
This is homework . I do not want the solution , just a small number of links or ideas.Simply speaking what I want to do is , Simple example : doThat ( ) is a method that is known to be time consuming , which results in my program blocking until results are back . And I want to use different methods of this Object , but...
public class Example { public void method ( ) { int x = doThat ( ) ; //Call other methods which do not depend on x return ; } }
Remove blocking from a method
Java
I have a strange problem with variable initialization.There is following code : What ? ? ? Variable is initialized , what is wrong ? also when I change org.junit.Assert.assertFalse to my own local method error disappears.I am using jdk 1.7.0_51 if that matters . Class code is here
public void test ( ) { StringBuilder buf ; org.junit.Assert.assertFalse ( ( buf = new StringBuilder ( `` qwe3 '' ) ) .toString ( ) .isEmpty ( ) ) ; org.junit.Assert.assertEquals ( `` '' , buf.toString ( ) ) ; // The local variable buf may not have been initialized } private static void assertFalse ( final boolean o ) t...
Strange variable initialization error
Java
I have following code : If fist string equals `` email '' I want to remove first string from the Stream . For other strings from the stream I do n't need this check.How could I acheve it ? P.S.Sure I can transform it to the list , then use old school for loop but further I need stream again .
Stream < String > lines = reader.lines ( ) ;
Remove first ( with zero index ) element from stream conditionally
Java
Is there any significant difference ( in performance or best practices ) between those two stream creation methods ? EDITThanks to Stack Community answers I can add some addons to question completeness for new readers : As many pointed out , .boxed ( ) IntStream method is defined as : What basically re-defines issue to...
int [ ] arr2 = { 1,2,3,4,5,6 } ; Arrays.stream ( arr2 ) .map ( ( in ) - > in*2 ) .mapToObj ( ( in ) - > new Integer ( in ) ) .collect ( Collectors.toCollection ( ( ) - > new ArrayList < > ( ) ) ) ; Arrays.stream ( arr2 ) .map ( in- > in*2 ) .boxed ( ) .collect ( Collectors.toCollection ( ( ) - > new ArrayList < > ( ) )...
Java 8 primitive stream to collection mapping methods
Java
when I open windows cmd and type jshell , it works , but when I 'm writing something . whenever I press the BackSpace key . for example if I want to delete a letter that is wrong . jshell crashes with bellow error , i 'm using windows 10 , and C : \Program Files\Java\jdk-11.0.1 is my only path in windows System Environ...
Exception in thread `` main '' java.lang.NullPointerException : charsetName at java.base/java.lang.String. < init > ( String.java:464 ) at java.base/java.lang.String. < init > ( String.java:537 ) at jdk.internal.le/jdk.internal.jline.extra.AnsiInterpretingOutputStream.write ( AnsiInterpretingOutputStream.java:92 ) at j...
Jshell crashes when i press BackSpace button in windows cmd
Java
I have defined a function in Kotlin : I have defined a Java method with this signature : I attempt to compose them like so : When I compile I get this error : Error : ( ln , col ) java : unreported exception java.io.IOException ; must be caught or declared to be thrownHow do I define my function parameters to accept a ...
fun convertExceptionToEmpty ( requestFunc : ( ) - > List < Widget > ) : Stream < Widget > { try { return requestFunc ( ) .stream ( ) } catch ( th : Throwable ) { // Log the exception ... return Stream.empty ( ) } } List < Widget > getStaticWidgets ( ) throws IOException ; Stream < Widget > widgets = convertExceptionToE...
How do I declare a function parameter to accept functions that throw ?
Java
I have list of students.I want to return list of objects StudentResponse classes that has the course and the list of students for the course.So I can write which gives me a map Now I have to iterate through the map again to create a list of objects of StudentResponse class which has the Course and List : Is there a way...
Map < String , List < Student > > studentsMap = students.stream ( ) . .collect ( Collectors.groupingBy ( Student : :getCourse , Collectors.mapping ( s - > s , Collectors.toList ( ) ) ) ) ; class StudentResponse { String course ; Student student ; // getter and setter }
Flatten a map after Collectors.groupingBy in java
Java
I have a method which takes String argument . In some cases I want to pass int value to that method . For invoking that method I want to convert int into String . For that I am doing the following : One more option is : Both are correct . I do n't know which is appropriate ? Which gives better performance ? Mostly this...
aMethod ( `` '' +100 ) ; aMethod ( String.valueOf ( 100 ) ) ;
String conversions in Java
Java
As of now I have an object that looks similar to the below . Background : The problem is with this last toJSON function . I have two different functions ( listed here as TakesADataObjOrCollectionOfDataObjs and TakesAnObjectOrCollection ) which do different things based on if the object implements JSONable or not . Now ...
public class DataField implements JSONable { public final String name ; public final Class < ? > typeClass ; private Object data ; public < T > DataField ( String name , Class < T > typeClass ) { this.name = name ; this.typeClass = typeClass ; data = null ; } public < T > T getData ( Class < T > passClass ) { if ( ! ty...
Java doing different things based on generic type
Java
I 'm seeing an extremely strange issue with Maven today : it 's trying to build classes that are not in my project , but coming from dependencies . mvn compile crashes with : There is no AppConstants.java in my project , and a search with grep -r AppConstants . gives no results . The class exists in another artifact th...
... [ ERROR ] COMPILATION ERROR : [ INFO ] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - [ ERROR ] AppConstants.java ) : [ 4,12 ] unmappable character for encoding UTF-8 ... $ grep -ri AppConstants . # finds nothing $ find . | grep -i AppConstants # finds nothing
How is it possible that Maven builds classes that are not in my project ?