Tag Info

New answers tagged java

0

Just some idea. 32 = 25, so n = 2k where integer k <= 5. k = -2 for 0.26. That allows integer arithmetic to some degree, diminishing floating point errors.

-3

In my opinion, your code is too long to solve this specific problem. I'm not much into Java, but I would try the following methods: Use "Trie" like data structure. As the length of the IP is always less than or equal to 12, so it should also do the job. This method will require a very small amount of memory. First of all, build the trie, insert ...

5

I see one little problem with the code you gave, even though I feel like it's a pretty good take at the problem you have. Best case/worst case, you always ask for 512Mb memory. Say I give you a file that has 1 million times the same address, the code still initialized a 514 megabytes array. Instead of using an array structure, I believe a tree structure ...

7

Since it's a job interview question, you probably want to: specify a package instead of using the default one. E.g. package chpter.one; put only the necessary code (BitSetUniqueIpCounter.java, IpCounterApp.java, UniqueIpCounter.java) in src/main/java. Anything that is only used for tests should be in src/test/java or src/test/resources/. Don't forget to ...

4

consuming as little memory and time as possible While your one bit per possible address is decent, it's not as little as possible. I actually have to run Java with -Xmx to allow it to take more heap space than usual. An alternative idea: Go through the file, parse the addresses, and store them in temporary files. For example the address 1.2.3.4 goes into ...

0

I think Timothy Truckle has covered a lot of good ground here. I'd disagree with the idea of throwing an unchecked exception when entries can't be found, however. This exercise has very similar characteristics to the java.util.Map interface (in fact, if the OP wasn't specifically focussing on learning ArrayLists, a Map would be a better structure with which ...

8

I'm agree with TorbenPutkonen's considerations about your code and with Manuel's observation about edge ipaddresses cases like 255.255.255.255 that can break your code, I focused about your method toLongValue translating your ipv4 address to an unique long: static long toLongValue(String ipString) { StringBuilder field = new StringBuilder(3); int ...

16

I'm being extra pedantic as this is a job interview question. Your code is better than 90% of what I have seen in job interviews. It shows that you have a fairly good understanding of how to solve the problem but there are improvements to be made in both minor details and the overall design of the solution. (This answer is a bit unstructured as I just make ...

15

The maximum int value is $2^{31}-1$, so your BitSets have $2^{31}-1$ entries each, so together they only cover $2^{32}-2$ IPs, missing two. And you documented their ranges incorrectly. If the file contains 255.255.255.255, you crash like this: Exception in thread "main" java.lang.IndexOutOfBoundsException: bitIndex < 0: -2147483648 at ...

4

What I like You follow the Java Naming conventions and the names you choose for your identifiers are pretty good. What I don't like Unnecessary mutability The member variable phoneNumber in your class MobilePhone does not change during the objects life time, therefore it should be declared final. The same applies to name and phoneNumber in your class Contact....

1

You don't need to manually manage nested for loops. int[][] pixels = new int[100][100]; for (int[] row : pixels) { Arrays.fill(row, 1); } for (int i = 20; i < 50; i++) { Arrays.fill(pixels[i], 20, 50, 0); } This will make better use of optimizations available for managing array values. I personally don't like arr as a name for an array. If I ...

3

The constants of an enum are full featured classes. This means, in any of that constants you can override any non private method of the enum class itself and change the behavior to something constant specific. Basically this is the OO best practice exchange branching with inheritance. So the approach would be to make filterIsSecond() non static and add an ...

2

"I would like to increase the speed of the SHA256 algorithm" You're using a library for the hash so there's really no way for you to make it faster. In theory, if you're an expert in cryptography and in computer science you could maybe build something faster yourself but most likely it'll be slower because it's actually hard... From the resources I ...

1

When we use stream we do have more flexibility, like map ⟶ convert any array object to string filter ⟶ remove when it is empty join ⟶ add joining character //Deduplicate the comma character in the input string String[] splits = input.split("\\s*,\\s*"); return Arrays.stream(splits).filter(StringUtils::isNotBlank).collect(Collectors....

0

Review private final int x; and private final int y; part in Cell.java, do you consider to use Point2D class? In CellMap class, do you expect the value null is returned if the location passing into public Cell getNeighbor(AdjacentDirection dir, int x, int y) method is out of boundary? Or IllegalStateException can be used here?

8

As a long-term Java programmer, I know that most of my time will be spent in maintenance. On that basis I prefer simple code that expresses its purpose clearly to clever, concise, unclear code. With that context in place here's some basic comments. String a="a", b="b", c="c", d="d"; It's not the Java way to do ...

5

Since you are looking for a more concise way, you can use a for-loop with an empty body: boolean isGapLessHierarchy(String... args) { int i = args.length - 1; for (; i >= 0 && args[i].isBlank(); i--); for (; i >= 0 && !args[i].isBlank(); i--); return i == -1; } This also removes the need for the variable isGapless. With ...

2

What I'd recommend: If Gapless, only a single complete iteration of the sequence is required. Otherwise, checks till the first gap found. private boolean isGapLessHierarchy(String... args) { //Hierarchy int i=args.length-1; while(args[i].isBlank() && i>=0) //till data is found i--; for(--i; i>=0; i--) ...

1

Welcome to Stack Review, the first thing I see in your code is: class result { ..your code } Instead of result you should use Result as a classname because as specified in java_naming_conventions : Class names should be nouns, in mixed case with the first letter of each internal word capitalized. The second thing I see in your code is: HashSet<String> ...

1

Code looks clean, some variables should maybe have a little bit better name, some comments would be nice, overall very good for your first game. Some points: You should use a package, this makes it also easier to create a jar, and jars are good for distributing programs/games. I would combine Start.java, GameFrame.java and GameBoard.java: and make class ...

1

Multi-threading isn't easy, and the original Java constructs - threads and monitors - provided only limited support. These days if I have to do significant management of threads, such as making them wait on each other, I am most likely to make use of the more modern java.util.concurrent constructs, such as latches and barriers. However, this task can ...

1

Nice solution, find below my suggestions. Creating a list from a set: List<Integer> listaLideresOrdenada = new ArrayList<Integer>(); listaLideresOrdenada.addAll(listaLideres); The set can be passed directly to the constructor of ArrayList: List<Integer> listaLideresOrdenada = new ArrayList<Integer>(listaLideres); Copying the input ...

1

When you find the \' sequence, you're handling it all in one go. This seems to be the source of your index++ issue. It also means that you've got the repeated else clause in there. A small improvement would be to only handle the \ when you encounter \', then handle the subsequent ' on the next pass around the loop. As far as I can tell handling for ' ...

3

I'd suggest a Solution based on regular expressions like this: import static org.junit.Assert.assertThat; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.hamcrest.CoreMatchers; import org.junit.Test; public class EscapeQuotesTest { Pattern escapedQuotePattern = Pattern.compile("(\\\\)?(')(')&...

5

On the whole, the code was easy to read, and the tests were concise (apart from the fully qualified be.imgn.common.base.Version.valueOf call. Here's a few things to think about. Object Lifetime The VersionParser class takes in a String and then provides a parse method which actually does the parsing work. However, this method can only ever be called once. ...

1

String extends Object type: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html This means that String's superclass is Object, so any function that requires an Object as parameter will accept String as parameter also. You can read here about inheritance for example: https://www.tutorialspoint.com/java/java_inheritance.htm

1

I don't know how to read java code (I'm a python person), but reading your post, I have a few suggestions for you. (Sorry if you have already done these, as I've said I don't know java.) It sounds like you are doing median of 9 every single time. I'd suggest doing median of 3 if the list size is less than 128, and if it's between 128-8192, median of 9 (...

0

Just one additional aspect not yet mentioned by the other answers so far. Don't use wildcard imports as in import java.awt.*; import java.awt.event.*; import javax.swing.*; They look so convenient, but there's a risk. Why? It creates possible ambiguities that you can't control. Imagine that e.g. in Java20 a new class javax.swing.KeyAdapter gets introduced. ...

0

Beside all hints that you might gather from PMD, Findbugs and Checkstyle? I would suggest to review the design. The inheritance of GamePanel is GamePanel extends JPanel implements ActionListener whearat inheritance is meant to be used for something that "is" something, and fields are used to use for something that "has" something. From ...

2

This is a side issue really, but if your client and server are running on the same machine you may want to consider using the loop back address "127.0.0.1" when connecting from the client, or having it as a command line parameter. It'll mean that you don't need to recompile the application every time you move machines / your DNS decides to ...

2

Is the Employee's UUID the best course of action here to avoid the case where you have similar objects? I never hear people discuss UUIDs Since your Associator relies on comparing Employees, using UUID seems better than using mutatable fields that do not clearly identify one and the same Employee. But let's keep in mind, that your Associator, which manages ...

0

With your code you'll get getInstance(database1) == getInstance(database2) which is obviously wrong, this points to a problem with your API. Using a singleton (poorly) is the likely cause here. There's good reason why singletons are discouraged. For your problem you really should have one instance created in your main that's then passed through to all ...

2

There are already links on this page to reasons why singletons should not be used. I will not repeat those. is it a good way to provide a singleton object from 3rd party library? No. Your singleton has an undocumented internal state which affects the processing of the input parameters. On the first invocation, the getInstance(String connectionString) methods ...

3

This is very readable. I noticed you had a XKCD random number generator there... int i = 1; I'm aware that the time signal is not related to keypress timings (e.g. you might make a direction change but not actually move for up to 75ms). In principle I guess you can tap the arrow keys and not move the snake if you do it quick enough, is that right? Also the ...

1

I am not expert in singleton but does the connectionString really change over the life of the application? Usually (I might be wrong) this string is declared with the final keyword.

1

Super short review; Your code should be mostly in nicely named methods, not main You call System.out.println(i); twice, which means you do not follow the fizzbuzz rules counter is not used, and I am not sure it should have been declared static Why write a test for isFizz/isBuzz and then never actually use them, this looks bizarre to an interviewer Also, ...

0

Thanks for sharing your code. Your code is a procedural approach to the problem. There is nothing wrong with procedural approaches in general, but Java is an object oriented (OO) programming language and if you want to become a good Java programmer then you should start solving problems in an OO way. But OOP doesn't mean to "split up" code into ...

1

..are any practices that I can improve and make the code cleaner.. There are! Don't over-enigeer While you can create all fancy strategies to check tic-tac-too rules; I think it is best to keep it as simple as possible. So checking rows, columns and diagonals hard-coded is, imho, not too bad here. Don't use String for state You should never use a String to ...

1

I hate this sort of hard-coded testing - there is usually a better approach to represent our data. A few thoughts come to mind. You don't stop players playing into an already occupied cell. Why not use a 2-d array (actually an array of arrays)? Then you can more naturally scan rows, columns, and even diagonals. If you score X as 1 and O as -1, then a ...

4

You don't use counter, isFizz() or isBuzz(), testFizzBuzz() calls to a fizzBuzz method which doesn't appear to exist. (Passing a boolean argument which seems illogical). Your code is formatted well, but the points above mean that a reviewer would doubt your competence. Have you shown us all your code? If not, why not? Did you compile, run and test your code? ...

2

If you happen to use a recent versions of Java, you can take avantage of text blocks, i.e. """ (which were introduced as a preview feature in Java 13). They greatly increase the readability of your code by getting the double quotes out of the way while being formattable with the formatted method (similar to String format) : String ...

Top 50 recent answers are included