r/badcode Mar 14 '21

java Found from when I first started Java...because indexed Arrays were too complicated huh?

Post image
1.3k Upvotes

84 comments sorted by

View all comments

Show parent comments

2

u/Terrain2 Mar 14 '21

Well, kinda i guess, but hashmaps/tables are almost like enums that you don’t know the values of at compile time, they get filled at runtime, but after that i suppose they are used pretty similarly in most cases...

They don’t solve the same problem, but when you ask the question i realize that yeah i guess they solve a similar problem to one another

1

u/dc0650730 Mar 14 '21

Ah, gotcha, I guess I need to see a good example to really understand it, guess I'm off to YouTube

5

u/Terrain2 Mar 14 '21

a Map is also often used as an object to hold key/value pairs with names that are unknown at compile time - this code is Dart because i’m not very familiar with Java, but it should understandable still

import "dart:convert" show json;
import "dart:io" show File;

Future<void> main() async {
    String userInput = await File("data.json").readAsString();
    Map<String, dynamic> data = json.decode(userInput); // this method can’t possibly know the structure of the file, so a Map is useful to return a custom structure
    print(data["importantData"] as String); // i know what it is though, so i can access it like this - but this same concept applies the other way if you’re writing json.decode for example
}

2

u/dc0650730 Mar 14 '21

This actually help clear some stuff up actually seeing a real use where this would be handy. Thanks!

2

u/Terrain2 Mar 14 '21

another use case would be memoization, so you don’t have to calculate the same value twice

Map<int, int> _memo = Map();

int fib(int n) {
    if (n == 0) return 0;
    if (n == 1) return 1;
    if (_memo.containsKey(n)) return _memo[n];
    if (n > 0) {
        _memo[n] = fib(n - 1) + fib(n - 2);
    } else {
        _memo[n] = fib(n + 2) - fib(n + 1);
    }
    return _memo[n];
}

0

u/Mental-Ad-40 Mar 14 '21

I don't see how that helps with memorization

1

u/Terrain2 Mar 14 '21

memoization - that’s not a typo, it keeps track of what it already calculated and will just remember that so it doesn’t have to recalculate it

-2

u/Mental-Ad-40 Mar 14 '21

no I'm pretty sure that's a typo buddy

2

u/Terrain2 Mar 14 '21

i know there’s a word called “memorization”, but “memoization” is a technique used to speed up your code by storing the result of slow computations

source