|
Is there a simple way to create a list of references to objects? A rough sketch of what I'm trying to do...code:
|
# ¿ Jul 15, 2009 19:22 |
|
|
# ¿ Apr 27, 2024 06:54 |
|
rhag posted:So in order to achieve your goal you should have your own object, with a setNeckbeards() method. Create one instance of that object, add it to the vector, set the neckbeards value to something else, and see it change everywhere that object is referenced. So, basically I need to... code:
Am I going to run into problems with failing to initialize "contents" if it's not a blocked primative?
|
# ¿ Jul 15, 2009 20:35 |
|
I've got a question about creating new objects within generics. What I'm trying to do can be boiled down to this:code:
code:
|
# ¿ Jul 18, 2009 00:27 |
|
I'm running out of heap space. To be fair, I'm throwing around a whole lot of aHugeFuckinArrayDeque.clone()'s, but I try to make sure I call aHugeFuckinArrayDeque.clear() before I do that, so I shouldn't have any more than two copies at a time (which I have more than enough RAM for). Without looking at my rats' nest of code, would you suspect that I'm failing to clear out something somewhere, or is it just Java failing to do garbage collection appropriately? Java's tutorial just says something like "The garbage collector does its job automatically when it determines that the time is right," which isn't really helping me understand what's going on.
|
# ¿ Aug 3, 2009 21:37 |
|
rjmccall posted:1. You have a memory leak. In a GCed environment, this means that you're preventing something from getting collected by holding a reference to it when you don't mean to. We can't help you debug this without looking at your "rats' nest of code", which I assure you no-one wants to do. Try a memory profiler. Okay, that's about what I figured. I'm going to start sifting through the code - someone else wrote an extension to my class, and we're both blaming each other for the fuckup. (Of course. ) Thanks. Ninja Edit: He forgot to set an upper bound to turn on infinite-loop detection, and I failed to pick up on it till now.
|
# ¿ Aug 3, 2009 23:00 |
|
I'm trying to create a class that keeps track of different types of costs that a system might incur. (Examples might be time taken, money spent, and incorrect solution penalties.) I'm writing the abstract/template class, and my users need to be able to define their own cost categories at (their) compile time. I thought a good solution would be to have them create an Enum of different cost types, as it would save both time and memory over having cost types represented as strings. I'd like to create my class using generics, but I'm a bit unsure how to proceed.code:
code:
|
# ¿ Aug 5, 2009 20:48 |
|
Are there any good guides/articles/tutorials about how the JVM is using RAM? I'm trying to compare the memory usage characteristics of a program written in Java with one written in Tcl, and I'm calling "ps h -p [PID] -o vsz" from within each at certain intervals to try to observe how much RAM each is using. Tcl grows more or less linearly with the number of "states" that I'm trying to keep track of, but Java just sits at/around 685 Mb the whole time, regardless of how much information I think I'm tracking. (Please be kind, as this post probably reveals how little I know about Java, Linux, and Physical/Virtual Memory, all in one go.)
|
# ¿ Aug 7, 2009 20:31 |
|
Gabbo posted:Hey! This did the trick! Tools->Folder Options->View->Uncheck "Hide extensions for known file types". (You might also want to "Show hidden files and folders," but that one's up to you.) This is always the first thing I do when I'm working in a new account on Windows - I've had way too many problems due to not knowing what my extension actually is.
|
# ¿ Aug 7, 2009 21:48 |
|
Shameful double post.
|
# ¿ Aug 7, 2009 22:06 |
|
Does anyone have any decent resources for explaining to me how Java works? I mean, I'm solid with syntax, object-oriented-ness, various patterns, concurrance/threading, etc, but I have no idea what the ClassLoader is or does, other than "It's a tool I can use to get files from /src/main/resources". My knowledge of Java is purely from being dropped into the middle of it and figuring things out, rather than any formal education I've ever received. I feel like I'm a pretty solid developer, but I've just got some embarrassing holes in my background knowledge that I really should get around to filling in.
|
# ¿ Jul 12, 2013 02:24 |
|
Horse Cock Johnson posted:Can anyone recommend some good books or other resources for a long time C# developer looking to gain a deeper understanding of Java? Concurrency in Practice is a very good java book. I'm also a fan of Effective Java. Despite being 7 and 5 years old, they're still pretty relevant. The latest Java Version is Java SE 7, out in 2011, which... doesn't really contain a lot that's super interesting. Just some convenience stuff - Strings in switch statements, ways to represent binary literal integers, etc. Java 6, out in 2006, was the last big change, and Java 8 (2014?) is going to have a lot of convenience stuff for lamdas and functional-ish programming, which will be great to work with. It has been my experience, starting out with Java about a year ago, that familiarizing myself with the Apache Commons and Google Guava libraries has been incredibly useful. They contain the things that should be in core Java but aren't. Gravity Pike fucked around with this message at 21:44 on Jul 29, 2013 |
# ¿ Jul 29, 2013 21:40 |
|
Amarkov posted:
Generally, you're going to want to catch Exception instead of Throwable, unless you're able to handle things like OutOfMemoryError or StackOverflowError. Errors are generally unrecoverable, and your best bet is to let your program bail.
|
# ¿ Jul 30, 2013 22:14 |
|
Brain Candy posted:
... and at this point, I'm just going to use Uninterruptibles.sleepUninterruptibly(), because Guava includes
|
# ¿ Aug 1, 2013 09:52 |
|
So, simplified, you haveJava code:
Java code:
code:
code:
code:
|
# ¿ Aug 9, 2013 00:25 |
|
So, I guess I discovered something worth sharing with the class. In an attempt to write a kind-of-gross introspective "Bean Converter" :code:
code:
code:
For my utility function, type erasure is still a significant headache, but luckily I'm able to make some assumptions about instances of K extending an interface which exposes a map of <CollectionFieldName, CollectionFieldType>. Speaking of type erasure, boy is that inconvenient! I know it's not being addressed in any way in Java 8, but do any of you know if there are murmurings about ever resolving it? To my understanding, it's an artifact of not wanting to change Java Bytecode between 4 & 5, where Generics were introduced. Is this still a concern? Might we see somehthing in Java 9?
|
# ¿ Sep 11, 2013 06:38 |
|
Adventure Pigeon posted:I'm still pretty new to Java and have run into an issue. I'm working on writing a program that will determine the mean value for about 100000 datapoints by performing about 100 random simulations on each datapoint. I decided to mess around and see if I could multithread it to speed things up, so I tried to divide the datapoints up and pass them to separate threads, then perform the simulations for each batch of datapoints. I figured there'd be concurrency issues, and I want a separate instance of the variables for each thread, so I tried using ThreadLocal, but can't seem to make it work. The datapoints are stored in an ArrayList<String> and for the simulations, I've been randomizing the order by shuffling them. Apparently ThreadLocal doesn't like that. Anyways, if anyone has any ideas I'd appreciate them. It might be simpler to set things up to there just aren't any concurrency issues than it is to duplicate things among threads. The very best thing you can do if you're worried about concurrency issues is not write to a variable that might be under contention. Functions that don't mutate state are always thread-safe. (So List.get is safe, but List.set, List.add, and List.remove are not.) It's going to be hard to troubleshoot your problem without seeing any code. I'm not really sure what's going on from your description. It sounds like the datapoints are being partitioned out to different threads (so if ThreadA is working on the 3rd datapoint, that means that no other thread will be working on the 3rd datapoint), but then you're trying to create a copy of all of the datapoints and shuffle them within each thread?
|
# ¿ Sep 14, 2013 06:48 |
|
Adventure Pigeon posted:This is the primary class. It works aside from the method where I try to split things into threads using ExecutorService Not horrors; you're new, and still learning. I'd implement makeThreads as follows: Java code:
However, the main difference is that we're creating a new copy of things for each thread. new ArrayList(sourceList) creates an entirely separate list in memory, and changing this list doesn't cause the order or contents of any of the other lists to change. One of your bugs is that windowSegment always refers to the same list. When you passed it to a thread, you were almost immediately clearing that list's contents, and overwriting it with new contents. Java code:
Within each RunThreads instance, I'd consider creating a Random() in the constructor, and using the same Random object for each Collections.shuffle call. (Or just allow shuffle to use the default source of randomness.) Java code:
Java code:
From a Java-conventions standard, Classes are named with capitol letters and methods are named with lower-case letters. Gravity Pike fucked around with this message at 01:02 on Sep 15, 2013 |
# ¿ Sep 15, 2013 00:54 |
|
quote != edit
|
# ¿ Sep 15, 2013 01:00 |
|
Specifically the ArrayList<T>(Collection<? extends T> source) constructor creates a new list which contains the same objects as the source collection, in the same order that the source collection iterates over them. This means that you can create an ArrayList that contains the same elements that a Set contains, or the same elements that a LinkedList contains. It's worth noting that these are literally the same objects, and while modifying the source list won't modify the new ArrayList, modifying one of the Objects in the source list will modify the Object in every list. Strings are safe, because strings are immutable; they can't change. However, if you had: Java code:
|
# ¿ Sep 15, 2013 10:35 |
|
I hate to tell you to RTFM, but Java has really good documentation. You can basically google any classname, and among the first few results will be a detailed description of the class, it's complete hierarchy, and a complete description of all of it's methods.JavaDocs posted:public E remove(int index)
|
# ¿ Sep 15, 2013 21:57 |
|
Is plural class names a convention that anyone actually follows? I mean, it's not Lists<Dog> bestDogsList = new ArrayLists<Dog>();. The only place you see plural class names are the static "Utility" classes in Commons/Guava, where they really want to put a bunch of static methods in the parent class. (ie Lists.newArrayListWithExepectedSize(10);)
|
# ¿ Sep 18, 2013 18:39 |
|
Zeether posted:I went back and wrote a method for the word search which uses loops for each direction, but it doesn't work right and I tried debugging with println() to see what was wrong and got nothing out of it. The loops are most likely wrong but I'm not sure which way and I haven't made ones to check diagonals yet. Did you make a copy/paste error? wordCheck is never getting called. wordToFind is getting set within a loop, but never used. You've also got logic errors, but I kind of feel like you should work those out on your own. Learning a debugger is like a super essential skill, and it's pretty dang easy for straightforward cases like your own. Are you using an IDE, like Eclipse? Read this tutorial.
|
# ¿ Sep 26, 2013 02:49 |
|
KildarX posted:Thanks for the help guys been working on it steadily. Honestly, I wouldn't try to fit everything in one matcher. Regular Expressions are all about patterns, and that's not what you're interested in - you don't care whether the upper case letter comes before or after the digit, which is why you've got all of those bizarre non-capturing groups. I'd create 3 or 4 different patterns, and use Matcher.find() instead of Matcher.matches(). Here's a broad question/statement/poll: I really hate do/while's. Instead of: code:
code:
Gravity Pike fucked around with this message at 07:48 on Oct 4, 2013 |
# ¿ Oct 4, 2013 07:42 |
|
1337JiveTurkey posted:Check if the length of password.replaceFirst("\\d", "").replaceFirst("[a-z]", "").replaceFirst("[A-Z]", "") is 3 less than the original length. Dear everyone, I hate you. This is my loving code, don't you dare come near it. Miss me when I'm gone, Jive Turkey (I am kidding. (Exactly as much as you are))
|
# ¿ Oct 8, 2013 01:27 |
|
KildarX posted:So I need to read in a text file, which has lines in format " name; category; cost; date;" take like categories and add the costs up and out put them as totaled. Personally, I'd read in each line as a String, and use String.split() to split the input on the semicolon. I'd then use a Map<String, Float> to associate each category with it's sum of costs. @MrPablo: Since this is titled "lab 7", you should give hints, but probably avoid flat-out doing this guy's homework for him.
|
# ¿ Oct 25, 2013 21:24 |
|
KildarX posted:I guess I'm over thinking it again, thought I was gonna be clever using arrays and crap. So other people might fervently disagree with me on this statement, but, as a professional software developer: Never be clever. There are many things that you can optimize for in your code: speed, memory usage, source lines, compile size. The most important is maintainability. If you think you're being clever, the person sitting next to you is going to read the code and think that it's confusing. Clever code causes bugs. Clever code eats up dev-hours as people try to parse through your logic. Clever code usually fails to foresee the product requirement that is going to be thrown at the codebase a few months down the line. Clever code takes somewhere between two and ten times as long to update as boring, idiomatic code. By all means, be intelligent. Write smart code. But remember that your code is going to be read by other devs far more frequently that the one time that you write it. It not only has to produce the correct output, it has to, at a glance, look like it's going to produce the correct output.
|
# ¿ Oct 25, 2013 23:08 |
|
You are kind of missing out on the major positive aspects of inheritance in your sample classes: abstract methods. First off, inheritance means that you can stick a more-specific object in a less-specific variable: Java code:
Java code:
Put these two concepts together, and you can do things like: Java code:
|
# ¿ Oct 28, 2013 10:14 |
|
BexGu posted:Any one know of any java classes that do the same things (or similar) to this Python script? (Creating Human readable UUIDs) Google is turning up like 2 people who have done a Bubble Babble assignment. Beyond that, you might be best off reimplementing that Python script on your own.
|
# ¿ Nov 5, 2013 22:23 |
|
The Guava Throwables library has a nifty convenience operation for this use case:Java code:
Java code:
|
# ¿ Nov 12, 2013 19:38 |
|
I mean, absolutely, there is a science to propagating exceptions, and generally wrapping everything in a RuntimeException is the wrong thing to do. On the other hand, we have UnsupportedEncodingException. It is checked, and explicitly gives me a chance to react to it. Now, I'm asking for UTF-8. I know that I have access to UTF-8. It is utterly unreasonable to force everything at a higher level to deal with the possibility of an UnsupportedEncodingException. But it is also insanely unsafe to write code that would just swallow this exception, even though I know it'll never actually be thrown. So I wrap it in a RuntimeException, and get to ignore it, and still feel confident that the system isn't ignoring it, and it'll bubble up to a point where someone (the server framework, usually) will transform it into a useful response. (500 Server Error) (If you take issue with UnsupportedEncodingException in this instance, feel free to substitute NoSuchAlgorithmException.) The law of the land is to propagate checked exceptions that calling code has a reasonable expectation of being able to recover from. If one of my arguments is the encoding, yeah, pass along that Exception so maybe my caller can ask for a different one. But if you just bubble up every possibly thrown exception in your method signature, you're preventing your users from seeing what is actually likely, and obscuring their options for recovering from any given exception.
|
# ¿ Nov 13, 2013 01:22 |
|
Woodsy Owl posted:Is there an elegant way to escape the blocking java.net.ServerSocket.accept() ? I've got a thread dedicated to listening and it's got something like this going on: Disclaimer: I've never worked with sockets, and am approaching this purely as a "blocking call" problem. That being said, it seems to me like you could socket.setSoTimeout(somethingLow), and then just deal with your regular, expected SocketTimeoutExceptions. Java code:
Gravity Pike fucked around with this message at 23:09 on Nov 16, 2013 |
# ¿ Nov 16, 2013 22:24 |
|
Woodsy Owl posted:What's the goonsensus on this? I'm still following the Java style guide just because when I'm reworking the conditional's instructions I don't have to worry about forgetting to add brackets. In general, best practice is to follow the style guide, even where you personally disagree. If you're in an environment where you have a shared codebase (which basically every environment is, eventually), consistency plays a bigger role in readability than just about any other factor. Maybe you will remember to add the braces, but are you willing to bet that the next person to come along will? Will they be able to spot, at a glance, where their mistake is?
|
# ¿ Dec 8, 2013 06:50 |
|
Well, it seems that you've implemented a For-Switch, which is a common enough mistake that it's got its own wikipedia page. It's a good way to exercise both of those control structures, but you generally want to choose whether you're doing something sequentially or in a loop. ("Both" is the wrong answer.) In Comptuer Science we count starting at 0. In Java, we name classes starting with a capitol letter, in CamelCase, using full words. I can't see where you're using keybd to gather input at any point in time... unless it's in the Cat class? It's good practice to have "setter methods" accept an argument, rather than gather their own data. This way, you can load values from a database, or a text file, or by randomly generating them, and still use the same Cat class and setters. I implemented a simple solution before I re-read your line that says you don't use Arrays yet. (That is crazy. Using arrays makes this simpler.) Arrays (or their big-brothers, Collections) are the correct way to manage storage of many of the same type of thing. Java code:
Java code:
Java code:
Gravity Pike fucked around with this message at 08:16 on Dec 10, 2013 |
# ¿ Dec 10, 2013 08:13 |
|
Bullio posted:It meets the requirements, so I should get a proper grade for it, but I was hoping I could learn from you guys what I could do better with the tools at my disposal. Also, what books would you recommend? I like Java, but I'm really only relying on it as a stepping stone to learn how to program before focusing on learning another language entirely. The posts I've read here have been way informative and I look forward to delving deeper into the programming world. Effective Java is a great Java book, as is Java Concurrency in Practice. The thing is, I'm not sure whether they'd be of a whole lot of use to you at this point; they expect kind of a lot of background knowledge that you just don't have yet, and they give you guidelines to solve problems that are beyond your skillset. Honestly, I'd probably go with the official Java Tutorials, paying a whole lot of attentions to "Getting Started" and "Language Basics." Having a very strong grasp of "Collections" is essential; these are your bread-and-butter tools for everyday programming. Date and Time functions are... well... there. Java's built-in Date object really isn't that great, tbh. (All the cool kids use the JodaTime library.) And don't discount Java completely; it's not the newest, hottest language, but it is mature, which means that a lot of us make a living writing Java code. There are libraries to do basically anything in Java, and tools that work well surrounding the platform. A good programmer is language-agnostic; they'll be able to write in basically any language, given a while to study up on it, and have two or three at their fingertips to perform a wide variety of tasks. Having been on the interview-loop for a while, at my company we're looking for developers who are solid in any language, have a decent grasp of a scripting language to do simple tasks, and are familiar enough with bash to do very simple tasks without even writing a program in the first place.
|
# ¿ Dec 11, 2013 06:41 |
|
Bash is the default linux terminal. Knowing how to pipe together simple commands like grep, sed, sort, uniq, wc in order to filter and reduce data is a very important skill to practice. Not a day goes by where I don't do something like log onto a load-balancer and, grep ' 500 ' load_balancer.log.2013-12-01* | grep -oP 'userid/\w+' | sort | uniq | wc -l to figure out how many unique users were affected by server errors in a given day. (Roughly, "Search through all files starting with load_balancer.log.2013-12-01 for lines containing ' 500 ', then take the parts of those lines that are the string 'userid/' followed by any number of letters and numbers, and then sort those alphabetically, and then remove duplicates, and then count the number of lines.") You could have written a Java program to do that, but you'd waste a whole lot of time worrying about things like reading from files, and looking up how to do directory manipulation, and deciding on data structures, and saving your code somewhere, and compiling, when you could have taken thirty seconds on the command line to do the same thing using tools that someone else already wrote. Command line skills are a bit harder to pick up than programming, because there's often not a class that specifically teaches them. On the other hand, each command tends to be very simple, and you only need to know a few commands in order to accomplish 90% of what you'd ever want to do from the command line.
|
# ¿ Dec 12, 2013 07:54 |
|
Sab669 posted:Any recommendations on some absolute bare-bones First Programming Language books for Java? My roommate is going into his second semester of Comp Sci and he's really struggling. Decided to wait until the last week of vacation to buy a book and try to get back into it before the next semester starts Honestly, I think the Oracle turorials are pretty decent. (Scroll down to "Trails Covering the Basics".) Comp Sci II doesn't cover anything more complicated than, like, Generic Collections, right? It's been forever.
|
# ¿ Jan 13, 2014 21:02 |
|
DholmbladRU posted:This seems pretty trivial but I cant figure it out. How do you keep carriage returns from being removed from bufferedreader? This is a perfect oppurtunity to use the Apache Commons IOUtils class: Java code:
Fake Edit: Also, if you're going to be looping through the file like that, you really ought use a StringBuilder instead of concatenating strings. Since a String is immutable, what that does is allocate memory for the first line, and write the first line's worth of characters to that memory. Then it allocates enough memory for the first two lines, and copies the first two lines worth of characters to that memory block. Then it allocates enough memory for the first three lines, and copies those three lines to memory... You end up writing something like (lines^2 * average-line-length) characters. If you use a StringBuilder, it saves a reference to each String, and only when you call toString does it allocate enough memory to hold everything put together. Java code:
|
# ¿ Jan 14, 2014 23:18 |
|
rhag posted:The java compiler (at least from Sun/Oracle) has been able to see these kind of patterns since jdk 1.4 or so. It generates code that is using the stringbuilder, no need to worry. Still, it is a good habit to have, to not concatenate strings just for the sake of it. Huh, that's neat. I knew the compiler could do that for things like Java code:
|
# ¿ Jan 15, 2014 07:20 |
|
There is a logical error, not a syntax error. (Syntax errors won't even compile in Java!) I have a feeling that you could catch your own error with a bit of testing. Tests should be simple. They should generally test one thing. Two is an easy number to work with in this case. Ask your program what 2^0, 2^1, 2^2, and 2^3 are. You're going to get wrong answers for some of them, but the pattern should make it pretty easy to work out what's happening.
|
# ¿ Jan 22, 2014 01:24 |
|
|
# ¿ Apr 27, 2024 06:54 |
|
Sagacity posted:I've been dicking around with Java recently and I ran into a weird problem. It is well-defined that the @Before methods of the superclass will be run before the @Before methods of any subclass; however, I have seen weird behavior if your subclass Overrides the superclass's setup method, and both are annotated @Before. ie Java code:
Gravity Pike fucked around with this message at 21:46 on Feb 1, 2014 |
# ¿ Feb 1, 2014 21:42 |